springboot整合websocket(数据解析)

按上节改造

1 依赖

解析工具

<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.76</version>
</dependency>

<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>

2 封装一个pojo

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Message
{
    private String operation;  //是用来标识类型的
    private String msg; //消息

    public Message setOperation(String operation)
    {
        this.operation = operation;
        return this;
    }

    public Message setMsg(String msg)
    {
        this.msg = msg;
        return this;
    }
}

3 修改OnMessage方法

说明一下
我这里去掉了OnOpen方法里面原有的东西
tip 是用来进入聊天室后保存用户名
msg是用来发送消息

@Log4j2
@Controller
@ServerEndpoint("/websocket")
public class BaseWebsocketController
{
    //onopen 在连接创建(用户进入聊天室)时触发
    @OnOpen
    public void openSession(Session session, EndpointConfig config)
    {
		//原来的东西去掉了
    }

    //响应字符串
    @OnMessage
    public void onMessage(Session session, String message)
    {
        //使用 fastjson 解析 json 字符串
        final Message data = JSONObject.parseObject(message, Message.class);
        //响应的信息
        final Message response = Message.builder()
                .operation(data.getOperation())         //将请求的 operation 放入
                .build();
        //根据不同的 operation 执行不同的操作
        switch (data.getOperation()) {
            //进入聊天室后保存用户名
            case "tip":
                session.getUserProperties().put("username", data.getMsg());
                sessions.put(session.getId(), session);
                response.setMsg("[" + data.getMsg() + "]进入房间");
                sendAll(JSONObject.toJSONString(response));
                break;
            //发送消息
            case "msg":
                final String username = (String) session.getUserProperties().get("username");
                response.setMsg("[" + username + "]" + data.getMsg());
                sendAll(JSONObject.toJSONString(response));
                break;
        }
    }
}

4 页面的改造

html不变,我这里就只放script的东西了

修改了 webSocket.onopen
修改了 webSocket.onMessage
修改了 $(’#sendBtn’).click()
添加了 function sendMessage(operation, msg){}

<script>
    let webSocket;
    //ip和端口号用自己项目的
    //{websocket}: 其实是刚刚那个@ServerEndpoint("/websocket")中定义的
    let url = 'ws://127.0.0.1:8080/websocket';
    
    $('#username').keyup(function (e) {
      let keycode = e.which;
      if (keycode == 13) {
        $('#joinRoomBtn').click();
      }
    });
    
    //进入聊天室
    $('#joinRoomBtn').click(function () {
      let username = $('#username').val();
      webSocket = new WebSocket(url);
      webSocket.onopen = function () {
        console.log('webSocket连接创建。。。');
        sendMessage('tip', username);
      }
      webSocket.onclose = function () {
        console.log('webSocket已断开。。。');
        $('#messageArea').append('websocket已断开\n');
      }
      webSocket.onmessage = function (event) {
        //这个 data 和刚刚的 Message 一样
        let data = {
          operation: '',
          msg: ''
        };
  
        data = JSON.parse(event.data);
        switch (data.operation){
          case "tip":
            $('#messageArea').append(data.msg + '\n');
            break;
          case "msg":     //显示消息
            $('#messageArea').append(data.msg + '\n');
            break;
        }
      }
      webSocket.onerror = function (event) {
        console.log(event)
        console.log('webSocket连接异常。。。');
      }
    });
    
    //退出聊天室
    $('#leaveRoomBtn').click(function () {
      if (webSocket) {
        //关闭连接
        webSocket.close();
      }
    });
    
    //发送消息
    $('#sendBtn').click(function () {
      var msg = $('#sendMessage').val();
      if (msg.trim().length === 0) {
        alert('请输入内容');
        return;
      }
      sendMessage('msg', $('#sendMessage').val());
      
      $('#sendMessage').val('');
    });
    
    //发送消息
    function sendMessage(operation, msg) {
      //这个 data 和刚刚的 Message 一样
      let data = {
        operation: operation,
        msg: msg,
      };
      
      //将 data 转成 json 字符串
      webSocket.send(JSON.stringify(data));
    }
  
  </script>

版权声明:本文为qq_37705525原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。