Springboot集成WebSocket

Springboot集成WebSocket

  1. 导包
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-websocket</artifactId>
        </dependency>
  1. 注册bean
package com.example.demo.ws;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration
public class WsConfiguration {
    @Bean
    public ServerEndpointExporter getServerEndpointExporter() {
        return new ServerEndpointExporter();
    }
}
package com.example.demo.ws;

import com.example.demo.pojo.Message;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
@ServerEndpoint("/chat/{username}")
@Component
public class Ws {
    public static ObjectMapper mapper = new ObjectMapper();
    public String username;
    public Session session;
    public static Map<String, Ws> map = new ConcurrentHashMap<String, Ws>();

    @OnOpen
    public void onOpen(Session session, @PathParam("username") String username) {
        this.session = session;
        log.info("建立新的连接{}", username);
        this.username = username;
        map.put(username, this);
    }

    @OnMessage
    public void onMessage(String message) throws JsonProcessingException {

        Message msg = mapper.readValue(message, Message.class);
        log.info("获取到客户端{}的一条消息:{}", this.username, msg);
        if ("system".equals(msg.getTo())) {
            groupSendMessage(mapper.writeValueAsString(msg));
        }
    }

    @OnClose
    public void onClose(Session session) {
        map.remove(this.username);
        log.info("{}端断开了连接", this.username);
    }

    public void groupSendMessage(String message) {
        map.keySet().forEach(username -> {
            try {
                map.get(username).session.getBasicRemote().sendText(message);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

    public void sendMessage(String username, String message) throws IOException {
        map.get(username).session.getBasicRemote().sendText(message);
    }
}

  1. 前端
<!DOCTYPE html>
<html lang="zh">
   <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title></title>
      <link rel="stylesheet" href="http://www.scsoul.top/layui/css/layui.css" />
      <style type="text/css">
         #chat-window {
            box-sizing: border-box;
            width: 750px;
            height: 600px;
            border: 1px solid darkgray;
            margin: 50px auto;
            position: relative;
         }

         #chat-window-head {
            user-select: none;
            cursor: auto;
            position: absolute;
            left: 0;
            top: 0;
            right: 0;
            height: 50px;
            line-height: 50px;
            font-size: 22px;
            color: #fff;
            text-align: center;
            background-color: deepskyblue;
            display: flex;
            justify-content: space-between;
         }

         .chat-window-online {
            font-size: 12px;
            color: #00000073;
         }



         #chat-window-body {
            position: absolute;
            left: 0;
            top: 50px;
            bottom: 100px;
            right: 0;
            overflow: auto;
            padding: 15px;
            box-sizing: border-box;
         }

         .message {
            display: block;
         }

         .message-left {
            text-align: left;
         }

         .message-right {
            text-align: right;
         }

         #msg {
            box-sizing: border-box;
            padding: 2px;
            width: 745px;
            height: 60px;
            border: none;
            resize: none;
         }

         #chat-window-foot {
            position: absolute;
            left: 0;
            bottom: 0;
            right: 0;
            height: 100px;
            font-size: 14px;
            color: #fff;
            text-align: center;
            border-top: 1px solid darkgray;
         }

         #chat-window-foot-btn {
            box-sizing: border-box;
            text-align: right;
            padding-right: 15px;
         }
      </style>
   </head>
   <body>

      <div id="chat-window">
         <div id="chat-window-head">
            <span></span>
            <p id="romote-name">JavaEE交流聊天室<span class="chat-window-online"></span></p>
            <div id="close" style="padding: 0 20px 0 0;">&times;</div>
         </div>
         <!-- 聊天框 -->
         <div id="chat-window-body">

         </div>
         <!-- 编辑框 -->
         <div id="chat-window-foot">
            <textarea id="msg" autofocus></textarea>
            <div id="chat-window-foot-btn">
               <button id="closeBtn" class="layui-btn layui-btn-sm layui-btn-primary">关闭</button>
               <button id="sendBtn" class="layui-btn layui-btn-sm layui-btn-normal">立即发送</button>
            </div>
         </div>
      </div>



      <script src="http://www.scsoul.top/js/jquery-3.4.1.js"></script>
      <script>
         $(function() {
            const username = new Date().getTime();
            //var ws = new WebSocket("ws://localhost:8848/chat/" + username);
            var ws = new WebSocket("ws://www.scsoul.top:8848/chat/" + username);
            //要发送的消息
            var sendMsg = "";
            //聊天框
            var chatWindowBody = $("#chat-window-body");

            ws.onmessage = function(e) {

               var resp = JSON.parse(e.data);
               console.log(resp);
               if (resp.from != username) {

                  var messageHtml =
                     `<div class="message">
                                 <p class="message-left">${resp.from}说:${resp.data}</p>
                              </div>`;
                  chatWindowBody.append(messageHtml);
               }

            }

            //发送消息具体业务逻辑
            var send = function() {
               sendMsg = $("#msg").val();
               if (sendMsg == "") {
                  $("#msg").focus();
                  return false;
               }
               var messageHtml = `<div class="message">
                              <p class="message-right">${sendMsg}</p>
                           </div>`;
               chatWindowBody.append(messageHtml);
               $("#msg").val("").focus();
               var message = messageFactory(sendMsg, username);
               ws.send(message)

            }
            //点击发送按钮
            $("#sendBtn").click(send)
            $("#msg").on("keyup", function(e) {
               if (e.keyCode === 13) {
                  send();
               }
            });
            $("#close").click(function() {
               $("#chat-window").hide();
            })

            function messageFactory(data, msgfrom, msgto) {
               var go = msgto;
               if (msgto == null) {
                  go = "system"
               }
               return JSON.stringify({
                  from: msgfrom,
                  to: go,
                  data: data
               })
            }
         })
      </script>
   </body>
</html>
上一篇:java – 聊天服务器:保存对话日志的最佳(优化)方式是什么


下一篇:我的MYSQL学习心得(九)