实现效果 两个客户端相互发消息:
0. 前端代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>websocket通讯演示</title>
</head>
<body>
<h3>发送消息</h3>
<input type="text" id="msg"/>
<input type="button" value="发送消息" id="sendMsg"/>
<h3>接收消息</h3>
<div id="receiveMsg" style="background-color: lightblue;">
</div>
<script type="application/javascript">
window.CHAT = {
socket: null,
init: function () {
//判断当前浏览器是否支持websocket
if (window.WebSocket) {
//实例化webSocket
window.CHAT.socket = new WebSocket("ws://127.0.0.1:8080/ws");
//设置websocket的各个生命周期方法
window.CHAT.socket.onopen = function () {
console.log("建立连接");
},
window.CHAT.socket.onclose = function () {
console.log("连接关闭");
},
window.CHAT.socket.onerror = function () {
console.log("发生错误");
},
window.CHAT.socket.onmessage = function (e) {
console.log("接收到消息:" + e.data);
var receiveMsg = document.getElementById("receiveMsg");
var html = receiveMsg.innerHTML;
receiveMsg.innerHTML = html + "<br/>" + e.data;
}
} else {
alert("当前浏览器不支持webSocket,请升级!");
}
},
chat: function () {
var msg = document.getElementById("msg");
window.CHAT.socket.send(msg.value);
}
}
window.CHAT.init();
var sendMsg = document.getElementById("sendMsg");
sendMsg.onclick = function () {
window.CHAT.chat();
}
</script>
</body>
</html>
?1. 引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
2. 配置类
package com.janet;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
/**
* @Description TODO
* @Author Janet
* @Date 2022-05-09
*/
@Configuration
public class WebSocketConfig {
/**
* 扫描项目中带有@ServerEndpoint的注解,转成websocket服务实例
* @return
*/
@Bean
public ServerEndpointExporter serverEndpointExporter(){
return new ServerEndpointExporter();
}
}
3. 服务类
package com.janet;
import io.netty.util.internal.ConcurrentSet;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
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.concurrent.atomic.AtomicInteger;
/**
* @Description TODO
* @Author Janet
* @Date 2022-05-09
*/
@ServerEndpoint("/ws")
@Component
@Slf4j
public class WebSocketServer {
/**
* 在线人数
*/
private static AtomicInteger personNum = new AtomicInteger();
/**
* 用来保存每个客户端对应的WebSocketServer实例
*/
private static ConcurrentSet<WebSocketServer> webSocketSet = new ConcurrentSet<>();
/**
* 每个客户端对应的连接会话,通过它来主动给客户端发送消息
*/
private Session session;
/**
* 当连接建立成功之后,会调用该方法
*
* @param session
*/
@OnOpen
public void onOpen(Session session) {
this.session = session;
webSocketSet.add(this);
personNum.incrementAndGet();
log.info("新用户上线,当前在线人数:{}", personNum.get());
}
@OnClose
public void onClose() {
webSocketSet.remove(this);
personNum.decrementAndGet();
log.info("用户下线,当前在线人数:{}", personNum.get());
}
@OnMessage
public void onMessage(String message, Session session) throws IOException {
log.info("来自客户{}的消息:{}", session.getId(), message);
for (WebSocketServer webSocketServer : webSocketSet) {
webSocketServer.session.getBasicRemote().sendText(session.getId() + "说:" + message);
}
}
}
这样就ok啦~
|