spring-boot-starter-websocket入门

理解 1 有些浏览器不支持或一些限制代理可以阻止http协议开启websocket;也有可能因为websocket打开过久自动关闭它 所以Spring Framework提供了基于的透明后备方案。 这些方案可以通过配置启用,不需要修改应用程序;

2 Spring Framework 4 包括一个新的spring-messaging 模块,其中包含Spring Integration项目的关键抽象,如Message,MessageChannel,MessageHandler等,可以作为这样的消息架构的基础。 该模块还包括一组用于将消息映射到方法的注释,类似于基于Spring MVC注释的编程模型。

后端实现:

@ServerEndpoint("/WebSocketServer")

public class ServerEndPoint808

{

@OnOpen

public void start(Sessionsession)

{

System.out.println("连接成功! " +session.getId());

}

@OnMessage

public void reMessage(Session session, Stringstr)

{

try

{

session.getBasicRemote().sendText(str+ " who areyou");

}

catch (IOExceptione)

{

e.printStackTrace();

}

}

@OnError

public void error(Session session, Throwablet){t.printStackTrace();}

@OnClose

public void close(){}

这个类作为WebSocket的一个服务端,@ServerEndpoint("/push")的annotation注释端点表示将WebSocket服务端运行在ws://[Server端IP或域名]:[Server端口]/项目/WebSocketServer的访问端点(这个类必须要有公共无参构造函数)

注意事项: @serverendpoint 其中value是必须参数 subprotocols encoder decoder configurator(后三个都是继承或实现接口再将完整类名作为参数值)

在一个端点类中,至多可以为三个方法标注@OnMessage注解

由于websocket的协议与Http协议是不同的,导致无法直接拿到session 可以添加@weblistener类实现ServletRequestListener 接口 重写modifyHandshake方法"((HttpServletRequest) sre.getServletRequest()).getSession()"

If you have to send messages thatare not responses, store the Session object as an instance variableof the endpoint class in the method annotated with@OnOpen

session可以basic与async两种remote变量 再调用变量的sendObject方法发送数据

前端实现:

<script type="text/javascript">
            var socket;
            if(typeof(WebSocket) == "undefined") {
                alert("您的浏览器不支持WebSocket");
                return;
            }

            $("#btnConnection").click(function() {
                //实现化WebSocket对象,指定要连接的服务器地址与端口
                socket = new WebSocket("ws://192.168.1.2:8888");
                //打开事件
                socket.onopen = function() {
                    alert("Socket 已打开");
                    //socket.send("这是来自客户端的消息" + location.href + new Date());
                };
                //获得消息事件
                socket.onmessage = function(msg) {
                    alert(msg.data);
                };
                //关闭事件
                socket.onclose = function() {
                    alert("Socket已关闭");
                };
                //发生了错误事件
                socket.onerror = function() {
                    alert("发生了错误");
                }
            });
            
            //发送消息
            $("#btnSend").click(function() {
                socket.send("这是来自客户端的消息" + location.href + new Date());
            });
            
            //关闭
            $("#btnClose").click(function() {
                socket.close();
            });
        </script>

参考地址:

以上是原生的WebSocket使用

stomp支持下的websocket:

经验分享 程序员 微信小程序 职场和发展