分享

js websocket技术总结

 hncdman 2023-02-03 发布于湖南

马井堂

于 2021-12-16 16:47:50 发布

1360

 收藏 1

文章标签: websocket javascript 前端

版权

1、前端页面

前端页面是websocket连接请求端,在定有的url发起连接请求

Var ws;

  url="ws://localhost:8080/realtimeMonitor/websocket/hello";

ws=new WebSocket(url);

websocket有四个响应事件(onopen,onclose,onmessage,onerror),两个方法(close(),send())。

ws.onopen = function () {

         console.log('Info: connection opened.');

ws.onmessage = function (event) {

          console.log("收到消息!"+event.data);

ws.onclose = function (event) {

console.log('Info: connection closed.'); 

};

  }


其中onmessage响应事件是收到后台发来的数据,对数据做实时处理就可以在这里做;而send()方法则是前端对后台发数据,在项目中可以发送sensorNum以验证和查看和sensorNum数据匹配的data,减少后台向前台发送的数据量。

2、Web.xml配置

遇到的问题1:

要建立一个处理上述url的websocketServlet,但是项目中有一个jerseyServlet处理”/rs/”,所以如果直接用”/”,根据处理的优先级,会先由websocketServlet匹配,导致http://localhost:8080/realtimeMonitor/login.html ,也由websocketServlet处理,使项目无法登陆;

解决方案

二:在jerseyServlet中配置1,在websocketServlet处理“/websocket/”。

遇到的问题2:

无法找到websocketServlet的servlet-class,

解决方案

提升spring的版本由原来的3.2.5.RELEASE提升到4.0.1.RELEASE以上(我采用的是4.0.2.RELEASE)在paltform目录下的pom.xml中将

<spring.version>3.2.5.RELEASE</spring.version>

改成

<spring.version>4.0.2.RELEASE</spring.version>

Web.xml中添加的代码为:

<servlet>

        <servlet-name>websocketServlet</servlet-name>

        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

        <init-param>

            <param-name>contextConfigLocation</param-name>

            <param-value>classpath*:META-INF/spring/websocketmessage-applicationContext.xml</param-value>

        </init-param>

        <async-supported>true</async-supported>

    </servlet>

    <servlet-mapping>

        <servlet-name>websocketServlet</servlet-name>

        <url-pattern>/websocket/*</url-pattern>

    </servlet-mapping>


3、spring配置

也就是上述classpath*:META-INF/spring/websocketmessage-applicationContext.xml,前面已将url="ws://localhost:8080/realtimeMonitor/websocket/hello"处理到“ws://localhost:8080/realtimeMonitor/websocket/”要使spring配置产生作用,需配置websocket的匹配路径path,同时要配置对此path下前端和服务端的握手处理类和对此path的消息处理类。

问题三

无法配置websocket,

解决方案

添加域名

xmlns:websocket="http://www./schema/websocket"

       xsi:schemaLocation="

        http://www./schema/beans http://www./schema/beans/spring-beans.xsd

        http://www./schema/websocket http://www./schema/websocket/spring-websocket.xsd"


4、后台java

一、握手处理类

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override

public boolean beforeHandshake(ServerHttpRequest request,

    ServerHttpResponse response, WebSocketHandler wsHandler,

                 Map<String, Object> attributes) throws Exception {

        System.out.println("Before Handshake");

        return super.beforeHandshake(request, response, wsHandler, attributes);

    }

    @Override

    public void afterHandshake(ServerHttpRequest request,

            ServerHttpResponse response, WebSocketHandler wsHandler,

               Exception ex) {

        System.out.println("After Handshake");

        super.afterHandshake(request, response, wsHandler, ex);

    }

}



二、消息处理类

public class WebsocketEndPoint extends TextWebSocketHandler {

    @Override

    protected void handleTextMessage(WebSocketSession session,

                                     TextMessage message) throws Exception {

        super.handleTextMessage(session, message);

    }

}


要使上述运行正常在pom.xml中添加

<dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-webmvc</artifactId>

            <version>${spring.version}</version>

        </dependency

<dependency>

            <groupId>org.springframework</groupId>

            <artifactId>spring-websocket</artifactId>

            <version>${spring.version}</version>

        </dependency>

1

2

3

4

5

6

7

8

9

10

要将项目中SocketTest中随机发的数据实时发送到前台,就必须将项目中JMS收到的数据实时结合消息处理类发送。

问题四:如果在JMS的onmessage中发送需要拿到websocket连接的session,如果在消息处理类中发送,如何实时触发消息处理类

解决方案:在消息处理类中定义全局变量tempSession,由前台onopen事件中send()方法触发产生一个session,将此保存到全局变量中,定义方法sendMessage(String request)在jms的onmessage中调用。最终消息处理类的代码为:

public class WebsocketEndPoint extends TextWebSocketHandler {

    private static WebSocketSession tempSession;

    private static String  tempMessage;

    @Override

    protected void handleTextMessage(WebSocketSession session,

                                     TextMessage message) throws Exception {

        tempSession = session;

        tempMessage = message.getPayload();

        super.handleTextMessage(session, message);

    }

    public void sendMessage(String  request) throws IOException {

        TextMessage returnMessage = new TextMessage(request);

        tempSession.sendMessage(returnMessage);

    }

    public String getTempMessage(){

        return tempMessage;

    }

}

JMS中的onmessage()添加的代码为:

  try {

       WebsocketEndPoint webSocket = new WebsocketEndPoint();

                    String sNum=webSocket.getTempMessage();

                    webSocket.sendMessage(messageText);

                } 

catch (Exception exception) {

                    exception.printStackTrace();

                }

前端js代码为:

function connect() {

            var url="ws://localhost:8080/realtimeMonitor/websocket/hello";

            ws = new WebSocket(url);

            ws.onopen = function () {

                console.log('Info: connection opened.');

                ws.send(currentMonitor.number);

            ws.onmessage = function (event) {

                console.log("收到消息!"+event.data);

                var sensorJumpName=eval("(" +event.data+ ")");

                var number=sensorJumpName.sensors[0].sensorNum;

                var data1=sensorJumpName.sensors[0].data;

            if(currentMonitor.number==number){

                  drawChart("#waveContainer", data1, "mV");

                }

            };

            ws.onclose = function (event) {

                console.log('Info: connection closed.');

                console.log(event); };

            }

        }

————————————————

版权声明:本文为CSDN博主「马井堂」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。

原文链接:https://blog.csdn.net/weixin_39501680/article/details/121977787

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多