pom
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
后端
@Component
@ServerEndpoint("/chat/{userId}")
public class ChatWebSocket {
/*
* 存储所有的在线人员信息
* */
private static ConcurrentHashMap<String,Session> cacheUser=new ConcurrentHashMap<>();
/**
*
* @param session 通道
* @param userId
*/
@OnOpen
public void onOpen(Session session, @PathParam("userId") String userId){
System.out.println("userId:"+userId+"上线了");
cacheUser.put(userId,session);
}
@OnMessage
public void onMessage(String message,Session session)throws Exception{
System.out.println("发送的消息"+message);
//根据指定的规则,拆分消息,获取消息发送给谁
String [] split=message.split(":",2);
Assert.state(split.length==2,"接受到的消息不合法");
//获取发送消息的人和消息
String toUser=split[0];
String msg=split[1];
//根据touser,查找指定的人的通道
Session to=cacheUser.get(toUser);
//如果找不到,那么给发送消息的人提示对方不在线
if(to==null){
session.getBasicRemote().sendText("对方不在线");
return;
}
//获取当前登录的账号用户
String userId=session.getPathParameters().get("userId");
//如果对方在线,将消息转发给对方
to.getBasicRemote().sendText(userId+":"+msg);
System.out.println("消息已经转发");
}
@OnClose
public void onClose(Session session){
String userId=session.getPathParameters().get("userId");
System.out.println(userId+"下线了");
cacheUser.remove(userId);
}
}
@Configuration
@EnableWebSocket
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
前端
客户端1
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<textarea id="msg"></textarea>
</body>
<script>
$(function(){
/* $.ajax({
url:"http://localhost:8082/demo/user/put"
}).then(res=>{
console.log(res)
}) */
let ws=new WebSocket("ws://localhost:85/chat/lisi");
$("#msg").on("keydown",function(event){
if(event.keyCode==13){
event.preventDefault();
let message=this.value;
if(message!==""){
//将消息发送给服务器
ws.send(`zhangsan:${message}`)
this.value="";
}
}
})
//接受服务器的消息
ws.onmessage=function(event){
console.log(event.data)
}
})
</script>
</html>
客户端2
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
</head>
<body>
<textarea id="msg"></textarea>
</body>
<script>
$(function(){
/* $.ajax({
url:"http://localhost:8082/demo/user/put"
}).then(res=>{
console.log(res)
}) */
let ws=new WebSocket("ws://localhost:85/chat/lisi");
$("#msg").on("keydown",function(event){
if(event.keyCode==13){
event.preventDefault();
let message=this.value;
if(message!==""){
//将消息发送给服务器
ws.send(`zhangsan:${message}`)
this.value="";
}
}
})
//接受服务器的消息
ws.onmessage=function(event){
console.log(event.data)
}
})
</script>
</html>