WebSocket实战

pom.xml

xml 复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-websocket</artifactId>
</dependency>

WebSocketConfiguration.java

java 复制代码
@Configuration
public class WebSocketConfiguration {
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }
}

ChatMessage.java

java 复制代码
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class ChatMessage {
    private Long senderId;
    private Long receiverId;
    private String content;
}

WebSocketServer.java

java 复制代码
@Slf4j
@Component
@ServerEndpoint("/ws/{userId}")
public class WebSocketServer {

    @Autowired
    private IChatService chatService;

    public static Map<Long, Session> sessionMap = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") Long userId) {
        log.info("用户: {} 与服务器建立连接", userId);
        sessionMap.put(userId, session);
    }

    @OnMessage
    public void onMessage(String message, Session senderSession, @PathParam("userId") Long senderUserId) {
        ChatMessage receivedMessage = JSON.parseObject(message, ChatMessage.class);
        chatService.persistChatMessage(receivedMessage);
        sendPrivateMessage(receivedMessage);
    }

    @OnClose
    public void onClose(Session session, @PathParam("userId") Long userId) {
        log.info("用户: {} 与服务器断开连接", userId);
        sessionMap.remove(userId);
    }

    private void sendPrivateMessage(ChatMessage message) {
        String jsonMessage = JSON.toJSONString(message);

        Session receiverSession = sessionMap.get(message.getReceiverId());
        if (receiverSession != null) {
            try {
                receiverSession.getBasicRemote().sendText(jsonMessage);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

chat.html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>User</title>
</head>
<body>
    <h2>User</h2>

    <div id="message-container">
        <h3>Received Messages:</h3>
        <ul id="received-messages"></ul>
    </div>

    <div>
        <h3>Send a Message:</h3>
        <label for="receiver-id">Receiver ID:</label>
        <input type="text" id="receiver-id" placeholder="Enter receiver's ID...">
        <br>
        <label for="message-input">Message:</label>
        <input type="text" id="message-input" placeholder="Type your message...">
        <button onclick="sendMessage()">Send</button>
    </div>

    <script>
        var userId = prompt("Enter your user ID:");
        var websocket = new WebSocket("ws://localhost:8080/ws/" + userId);

        websocket.onmessage = function (event) {
            var receivedMessages = document.getElementById("received-messages");
            var messageItem = document.createElement("li");
            var messageData = JSON.parse(event.data);
            messageItem.textContent = "From User ID " + messageData.senderId + ": " + messageData.content;
            receivedMessages.appendChild(messageItem);
        };

        function sendMessage() {
            var receiverIdInput = document.getElementById("receiver-id");
            var messageInput = document.getElementById("message-input");

            var receiverId = receiverIdInput.value;
            var messageContent = messageInput.value;

            if (receiverId && messageContent) {
                var message = {
                    senderId: userId,
                    receiverId: receiverId,
                    content: messageContent
                };

                websocket.send(JSON.stringify(message)); 	// 使用JSON.stringify()转换为JSON字符串
                messageInput.value = "";
            } else {
                alert("Please enter receiver ID and message before sending.");
            }
        }
    </script>
</body>
</html>
相关推荐
PyAIGCMaster25 分钟前
ubuntu装P104
服务器·网络·ubuntu
网络安全Jack2 小时前
什么是网络安全等级保护?
网络·安全·web安全
Dovir多多3 小时前
Python数据处理——re库与pydantic的使用总结与实战,处理采集到的思科ASA防火墙设备信息
网络·python·计算机网络·安全·网络安全·数据分析
VVVVWeiYee4 小时前
项目2路由交换
运维·服务器·网络·网络协议·信息与通信
小伍_Five6 小时前
透视网络世界:计算机网络习题的深度解析与总结【前3章】
服务器·网络·计算机网络
网络安全(king)8 小时前
网络安全攻防学习平台 - 基础关
网络·学习·web安全
李白你好8 小时前
家用无线路由器的 2.4GHz 和 5GHz
运维·网络
嵌入(师)8 小时前
嵌入式驱动开发详解21(网络驱动开发)
网络·驱动开发
柒烨带你飞9 小时前
路由器的原理
网络·智能路由器·php
xserver29 小时前
ensp 基于EASY IP的公司出口链路配置
网络·tcp/ip·智能路由器