导入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
工具类 WebSocketUtils
package com.dirk.websocket.utils;
import javax.websocket.RemoteEndpoint;
import javax.websocket.Session;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class WebSocketUtils {
public static final Map<String, Session> LIVING_SESSIONS_CACHE = new ConcurrentHashMap<>();
public static void sendMessageAll(String message) {
LIVING_SESSIONS_CACHE.forEach((sessionId, session) -> sendMessage(session, message));
}
public static void sendMessage(Session session, String message) {
if (session == null) {
return;
}
final RemoteEndpoint.Basic basic = session.getBasicRemote();
if (basic == null) {
return;
}
try {
basic.sendText(message);
} catch (IOException e) {
e.printStackTrace();
}
}
}
服务端 WebSocketController
package com.dirk.websocket.controller;
import com.dirk.websocket.utils.WebSocketUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
@RestController
@ServerEndpoint("/chat-room/{username}")
public class WebSocketController {
private static final Logger logger = LoggerFactory.getLogger(WebSocketController.class);
@OnOpen
public void openSession(@PathParam("username") String username, Session session) {
WebSocketUtils.LIVING_SESSIONS_CACHE.put(username, session);
String message = "欢迎用户[" + username + "] 来到聊天室!";
logger.info(message);
WebSocketUtils.sendMessageAll(message);
}
@OnMessage
public void onMessage(@PathParam("username") String username, String message) {
logger.info(message);
WebSocketUtils.sendMessageAll("用户[" + username + "] : " + message);
}
@OnClose
public void onClose(@PathParam("username") String username, Session session) {
WebSocketUtils.LIVING_SESSIONS_CACHE.remove(username);
WebSocketUtils.sendMessageAll("用户[" + username + "] 已经离开聊天室了!");
try {
session.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@OnError
public void onError(Session session, Throwable throwable) {
try {
session.close();
} catch (IOException e) {
e.printStackTrace();
}
throwable.printStackTrace();
}
@GetMapping("/chat-room/{sender}/to/{receive}")
public void onMessage(@PathVariable("sender") String sender, @PathVariable("receive") String receive, String message) {
WebSocketUtils.sendMessage(WebSocketUtils.LIVING_SESSIONS_CACHE.get(receive), "[" + sender + "]" + "-> [" + receive + "] : " + message);
}
}
入口启动类 WebsocketApplication
package com.dirk.websocket;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;
@SpringBootApplication
public class WebsocketApplication {
public static void main(String[] args) {
SpringApplication.run(WebsocketApplication.class, args);
}
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
前端聊天室界面 HTML
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>我的聊天室</title>
<script src="js/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var urlPrefix = 'ws://localhost:8080/chat-room/';
var ws = null;
$('#btn_join').click(function() {
var username = $('#in_user_name').val();
var url = urlPrefix + username;
ws = new WebSocket(url);
ws.onopen = function() {
console.log("建立 websocket 连接...");
};
ws.onmessage = function(event) {
$('#message_content').append(event.data + '\n');
};
ws.onclose = function() {
$('#message_content').append('用户[' + username + '] 已经离开聊天室!');
console.log("关闭 websocket 连接...");
}
});
$('#btn_send_all').click(function() {
var msg = $('#in_room_msg').val();
if (ws) {
ws.send(msg);
}
});
$('#btn_exit').click(function() {
if (ws) {
ws.close();
}
});
$("#btn_send_point").click(function() {
var sender = $("#in_sender").val();
var receive = $("#in_receive").val();
var message = $("#in_point_message").val();
$.get("http://localhost:8080/chat-room/" + sender + "/to/" + receive + "?message=" + message, function() {
alert("发送成功...")
})
})
})
</script>
</head>
<body>
<label for="message_content">聊 天 室 </label>
<textarea id="message_content" readonly="readonly" cols="57" rows="10" ></textarea>
<br />
<label for="in_user_name">用户姓名 </label><input id="in_user_name" value="" />
<button id="btn_join">加入聊天室</button>
<button id="btn_exit">离开聊天室</button>
<br />
<br />
<label for="in_room_msg">群发消息 </label><input id="in_room_msg" value="" />
<button id="btn_send_all">发送消息</button>
<br />
<br />
<br />
好友聊天
<br />
<label for="in_sender">发送者 </label>
<input id="in_sender" value="" />
<br />
<label for="in_receive">接受者 </label>
<input id="in_receive" value="" />
<br />
<label for="in_point_message">消息体 </label>
<input id="in_point_message" value="" />
<button id="btn_send_point">发送消息</button>
</body>
</html>
转载自:一起来学SpringBoot | 第二十五篇:打造属于你的聊天室(WebSocket)