需要引入maven
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
然后和其他不同的是需要写一个配置类 (唯一不同的地方)
@Configuration
public class SocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
附带贴一个后台代码
@Component
@ServerEndpoint("/websocket/{username}")
public class WebSocket {
public static int onlineCount = 0;
public static Map<String, WebSocket> clients = new ConcurrentHashMap<String, WebSocket>();
// public Session session;
public Session session;
public String username ;
@OnOpen
public void onOpen(Session session,@PathParam("username") String username) throws IOException {
this.session = session;
addOnlineCount();
clients.put(username, this);
// sendMessageAll(username+"进入了聊天室!\n"); //给全部的人发消息
System.out.println("connect !");
}
@OnClose
public void onClose() throws IOException {
clients.remove(username);
subOnlineCount();
}
@OnMessage
public void onMessage(String message) throws IOException {
System.out.println(message);
// sendMessageAll(message);
// JSONObject jsonTo = JSONObject.fromObject(message);
//
// clients.get("zhangxi").session.getAsyncRemote().sendText("张喜属猪的"); //给指定的人发消息
}
@OnError
public void onError(Session session, Throwable error) {
error.printStackTrace();
}
public static void sendMessageTo(String message, String To) throws IOException {
System.out.println("clients:\n"+clients);
WebSocket.clients.get("zhangxi").session.getAsyncRemote().sendText(message);
}
public void sendMessageAll(String message) throws IOException {
for (WebSocket item : clients.values()) {
item.session.getAsyncRemote().sendText(message);
}
}
public static synchronized int getOnlineCount() {
return onlineCount;
}
public static synchronized void addOnlineCount() {
WebSocket.onlineCount++;
}
public static synchronized void subOnlineCount() {
WebSocket.onlineCount--;
}
public static synchronized Map<String, WebSocket> getClients() {
return clients;
}
}
都贴了后台了 那就顺便贴一个前端代码
function getconn() {
var websocket = null;
var username = document.getElementById("name").value;
//判断当前浏览器是否支持WebSocket
if ('WebSocket' in window) {
// websocket = new WebSocket("ws://localhost:8080/unnamed/websocket/"+username);
// websocket = new WebSocket("ws://localhost:8080/unnamed");
websocket = new WebSocket("ws://localhost:9696/websocket/" + username);
// alert("当前浏览器支持");
} else {
alert('当前浏览器 Not support websocket');
}
//连接发生错误的回调方法
websocket.onerror = function () {
alert("发生错误");
// setMessageInnerHTML("WebSocket连接发生错误");
};
//连接成功建立的回调方法
websocket.onopen = function () {
alert("链接成功");
// var msg = "{\"To\": \"tom\"}"
// websocket.send(msg)
// setMessageInnerHTML("WebSocket连接成功");
}
//接收到消息的回调方法
websocket.onmessage = function (event) {
// alert("j接收到消息");
// alert(event.data);
document.getElementById("textarea").value +=event.data+"\n";
// setMessageInnerHTML(event.data);
}
//连接关闭的回调方法
websocket.onclose = function () {
alert("连接关闭");
// setMessageInnerHTML("WebSocket连接关闭");
}
//监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
window.onbeforeunload = function () {
closeWebSocket();
}
//关闭WebSocket连接
function closeWebSocket() {
websocket.close();
}
}