webSocket配置类
package com.example.websocket.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@Configuration
public class WebSocketConfig
{
@Bean
public ServerEndpointExporter serverEndpointExporter()
{
return new ServerEndpointExporter();
}
}
webSocket实时聊天类
package com.example.websocket.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
@Slf4j
@Component
@ServerEndpoint(value = "/websocket/{userId}/{receiveUserId}")
public class MyWebSocket {
public static MyWebSocket webSocketServer;
@PostConstruct
public void init(){
webSocketServer = this;
}
public static int onlineNumber = 0;
private static ConcurrentHashMap<Long,MyWebSocket> webSocketMap = new ConcurrentHashMap<>();
private Session session;
private Long userId;
private Long receiveUserId;
@OnOpen
public void onOpen(Session session, @PathParam("userId") Long userId, @PathParam("receiveUserId") Long receiveUserId) {
this.session = session;
this.userId=userId;
this.receiveUserId=receiveUserId;
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
webSocketMap.put(userId,this);
}else {
webSocketMap.put(userId,this);
addOnlineCount();
log.info("用户连接:"+userId+",当前在线人数为:" + getOnlineCount());
}
sendMessage("连接成功");
}
@OnClose
public void onClose() {
if(webSocketMap.containsKey(userId)){
webSocketMap.remove(userId);
subOnlineCount();
}
log.info("用户退出:"+userId+",当前在线人数为:" + getOnlineCount());
if(webSocketMap.containsKey(receiveUserId)){
webSocketMap.remove(receiveUserId);
subOnlineCount();
}
log.info("用户退出:"+receiveUserId+",当前在线人数为:" + getOnlineCount());
}
@OnMessage
public void onMessage(String message, Session session) {
log.info("用户消息:"+userId+",报文:"+message);
if (!StringUtils.isEmpty(message)){
try {
if (webSocketMap.get(receiveUserId)!=null){
if (webSocketMap.containsKey(receiveUserId)){
webSocketMap.get(receiveUserId).sendMessage(message);
}else {
log.error("请求的userId:"+receiveUserId+"不在该服务器上");
}
}
}catch (Exception e){
e.printStackTrace();
}
sendMessage(message);
}
}
public void sendMessage(String message) {
try {
session.getBasicRemote().sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("用户错误:"+this.userId+",原因:"+error.getMessage());
error.printStackTrace();
}
public static synchronized int getOnlineCount() {
return onlineNumber;
}
public static synchronized void addOnlineCount() {
MyWebSocket.onlineNumber++;
}
public static synchronized void subOnlineCount() {
MyWebSocket.onlineNumber--;
}
}
html页面一对一聊天
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>welcome</title>
</head>
<body>
<div>你好</div>
自己<input id="my" type="text"/><br>
接收消息人<input id="receive" type="text"/><br>
<button onclick="start()">点击建立连接</button><br>
<div id="messageList" style="width: 300px;height: 300px;border: 1px solid black"></div>
<input id="sendMessage" style="height: 100px; width: 200px"/><button onclick="sendMessage()">点击发送</button>
</body>
<script>
var webSocket;
var my;
var receive;
function start(){
my = document.getElementById('my').value
receive= document.getElementById('receive').value
if (window.WebSocket) {
webSocket = new WebSocket("ws://localhost:3477/websocket/"+my+"/"+receive);
webSocket.onopen = function() {
webSocket.send("发送数据");
};
webSocket.onmessage = function (evt) {
var message = evt.data;
var h2 = document.createElement("h2")
h2.innerHTML = message
document.getElementById('messageList').appendChild(h2)
};
}
}
function sendMessage(){
webSocket.send(document.getElementById('sendMessage').value)
}
</script>
</html>
|