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>