公告
淡泊明志,宁静致远
网站资讯
本站文章字数合计
243.7k
本站Hexo版本
6.1.0
本站Node版本
16.14.2
本站已运行时间
最后更新时间

分类: java | 标签: websocket

springboot整合websocket

发表于: 2024-08-18 15:38:28 | 字数统计: 987 | 阅读时长预计: 4分钟

springboot整合websocket

  • pom.xml
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
  • SpringbootApplication.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringbootApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }
}
  • Constant.java
import java.util.HashMap;
import java.util.Map;

import javax.websocket.Session;

public class Constant {
    public static Map<Integer,Session> sessionMap = new HashMap();
}
  • Message.java
public class Message {

    private Integer sendUserId; //发送人id
    private String sendName; //发送人姓名
    private Integer receiveUserId; //接受人id
    private String receiveName; //接收人姓名
    private String content; //发送的的内容
    private String time = "2024-8-19 11:40:59"; //发送时间
    
    //get and set
}
  • WebsocketConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
@EnableWebSocket
public class WebsocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpoint() {
        return new ServerEndpointExporter();
    } 
}
  • WsServerEndpoint.java
import org.springframework.stereotype.Component;
import com.alibaba.fastjson.JSON;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@ServerEndpoint("/myWs")
@Component
public class WsServerEndpoint {
    
    /**
     * 查询字符串转map
     * @param queryString
     * @return
     */
    public static Map<String, String> queryStringToMap (String queryString) {
        Map<String, String> map = new HashMap<>();
        if (queryString == null || queryString.isEmpty()) {
            return map;
        }
        String[] pairs = queryString.split("&");
        for (String pair : pairs) {
            String[] keyValue = pair.split("=");
            if (keyValue.length == 2) {
                String key = keyValue[0];
                String value = keyValue[1];
                map.put(key, value);
            }
        }
        return map;
    }

    /**
     * 连接成功
     * @param session
     */
    @OnOpen
    public void onOpen(Session session) {
        Map<String, String> queryStringToMap = queryStringToMap(session.getQueryString());
        System.out.println(queryStringToMap);
        Integer currentUserId = Integer.parseInt(queryStringToMap.get("sendUserId").toString());
        Constant.sessionMap.put(currentUserId, session);
        System.out.println("连接成功"+queryStringToMap+Constant.sessionMap.keySet().size());
        try {
            session.getBasicRemote().sendText(queryStringToMap.get("sendName")+"上线了");
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    /**
     * 连接关闭
     * @param session
     */
    @OnClose
    public void onClose(Session session) {
        System.out.println("连接关闭");
    }
    /**
     * 接收到客户端发送的消息,转发到客户端
     * @param text
     */
    @OnMessage
    public void onMsg(String text) throws IOException {
        Message message = JSON.parseObject(text, Message.class);
        System.out.println("onMsg:"+message);
        System.out.print("sessionMap:"+Constant.sessionMap);
        String sendMsg = ""+message.getTime()+"   "+message.getSendName()+":"+message.getContent()+"  ";
        Constant.sessionMap.get(message.getSendUserId()).getBasicRemote().sendText(sendMsg); //发送人
        Constant.sessionMap.get(message.getReceiveUserId()).getBasicRemote().sendText(sendMsg); //接收人
//        return msg;
    }
}
  • websoket.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>WebSocket Chat</title>
    <style>
        #chat {
            border: 1px solid #ccc;
            height: 300px;
            overflow-y: scroll;
        }
        #messageInput {
            width: calc(100% - 50px);
        }
    </style>
</head>

<body>
    <div id="chat"></div>
    <input type="text" id="messageInput" placeholder="Type a message">
    <input type="text" id="sendUserIdInput" placeholder="你的id"></input>
    <input type="text" id="sendNameInput" placeholder="你的姓名"></input>
    <input type="text" id="receiveUserIdInput" placeholder="对方id"></input>
    <input type="text" id="receiveNameInput" placeholder="对方姓名"></input>
    <button onclick="linkMessage()">连接到WebSocket服务器</button>
    <button onclick="sendMessage()">发送</button>

    <script>
        const chat = document.getElementById('chat');
        const messageInput = document.getElementById('messageInput');
        const sendUserIdInput = document.getElementById('sendUserIdInput');
        const sendNameInput = document.getElementById('sendNameInput');
        const receiveUserIdInput = document.getElementById('receiveUserIdInput');
        const receiveNameInput = document.getElementById('receiveNameInput');

        let ws = null
        // 连接到WebSocket服务器
        function linkMessage() {
            const sendUserId = sendUserIdInput.value;
            const sendName = encodeURIComponent(sendNameInput.value);
            console.log('sendUserId', sendUserId,'sendName', sendName)
            ws = new WebSocket(`ws://localhost:8700/myWs?sendUserId=${sendUserId}&sendName=${sendName}`);
            // 接收WebSocket服务器的消息
            ws.onmessage = (event) => {
                console.log('event.data', event.data)
                const message = document.createElement('div');
                message.textContent = decodeURIComponent(event.data);
                chat.appendChild(message);
                chat.scrollTop = chat.scrollHeight; // 自动滚动到底部
            };
        }
        // 发送消息到WebSocket服务器
        function sendMessage() {
            const message = messageInput.value;
            const params = {
                sendUserId: sendUserIdInput.value,
                sendName: sendNameInput.value,
                content: message,
                receiveUserId: receiveUserIdInput.value,
                receiveName: receiveNameInput.value,
                time: new Date().toLocaleString()
            }
            if (message) {
                ws.send(JSON.stringify(params));
                messageInput.value = ''; // 发送消息后清空输入框
            }
        }
    </script>
</body>

</html>

websocket在线测试

http://coolaf.com/zh/tool/chattest

参考

java实现websocket的五种方式

------ 本文结束,感谢您的阅读 ------
本文作者: 贺刘芳
版权声明: 本文采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。