栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

js websocket技术总结

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

js websocket技术总结

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中将
3.2.5.RELEASE
改成
4.0.2.RELEASE
Web.xml中添加的代码为:


        websocketServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
            classpath*:meta-INF/spring/websocketmessage-applicationContext.xml
        
        true
    
    
        websocketServlet
        /websocket/*
    

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.springframework.org/schema/websocket"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/websocket http://www.springframework.org/schema/websocket/spring-websocket.xsd"

4、后台java
一、握手处理类

public class HandshakeInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
public boolean beforeHandshake(ServerHttpRequest request,
    ServerHttpResponse response, WebSocketHandler wsHandler,
                 Map 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中添加


            org.springframework
            spring-webmvc
            ${spring.version}
        
            org.springframework
            spring-websocket
            ${spring.version}
        

要将项目中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);			};
            }
        }
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/673082.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号