新建简单的springboot项目,引入socket相关的jar包
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<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>
在resources/templates/ws.html文件
注:(关闭掉这个页面之后,socket连接就会关闭)
//前后端分离的使用域名的时候,记得nginx把端口打开,因为springboot项目和websocket使用不同的端口,如果nginx没有打开websocket端口监听,前端是链接不上的
socket = new WebSocket("ws://localhost:8080/ws/asset");
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>websocket测试</title>
<style type="text/css">
h3, h4 {
text-align: center;
}
</style>
</head>
<body>
<h3>WebSocket测试</h3>
<h4>
单发消息
<li>url=http://localhost:8080/test/sendOne?message=单发消息内容&id=none</li>
群发消息
<li>url=http://localhost:8080/test/sendAll?message=群发消息内容</li>
</h4>
<div style="text-align:center;">
<textarea id="content" style="width:500px;height:300px;"></textarea></div>
<script type="text/javascript">
var socket;
if (typeof (WebSocket) == "undefined") {
console.log("遗憾:您的浏览器不支持WebSocket");
} else {
console.log("恭喜:您的浏览器支持WebSocket");
//实现化WebSocket对象
//指定要连接的服务器地址与端口建立连接
//注意ws、wss使用不同的端口。我使用自签名的证书测试,
//无法使用wss,浏览器打开WebSocket时报错
//ws对应http、wss对应https。这个地址是endpoint定义的地址
//前后端分离的使用域名的时候,记得nginx把端口打开
socket = new WebSocket("ws://localhost:8080/ws/asset");
//连接打开事件
socket.onopen = function () {
console.log("Socket 已打开");
//可以在建立连接的时候,把用户名等相关信息发送到后台,后台就能根据不同用户登录处理逻辑
socket.send("消息发送测试(From Client)");
};
//收到消息事件
socket.onmessage = function (msg) {
var ta = document.getElementById('content');
ta.value = ta.value + '\n' + event.data
};
//连接关闭事件(关闭掉这个页面之后,socket连接就会关闭)
socket.onclose = function () {
console.log("Socket已关闭");
};
//发生了错误事件
socket.onerror = function () {
alert("Socket发生了错误");
}
//窗口关闭时,关闭连接
window.unload = function () {
socket.close();
};
}
</script>
</body>
</html>
真实页面,启动项目之后访问:http://localhost:8080/ws
webmvc的视图控制器配置
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/ws").setViewName("/ws");
}
}
websocket的ServerEndpointExporter
@Configuration
public class WebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
群发和单发消息调用的接口:
@RestController
@RequestMapping("/test")
@EnableScheduling
public class WsController {
/**
* 群发消息接口
* @param message
* @return
*/
@GetMapping("/sendAll")
public String sendAll(@RequestParam String message){
WebSocketServer.broadCastInfo(message);
return "ok";
}
/**
* 服务器定时群发消息
* @return
*/
@Scheduled(cron = "0/5 * * * * ? ")
public String sendAll(){
WebSocketServer.broadCastInfo("浏览器收到消息:服务端定时群发消息");
return "ok";
}
/**
* 单发消息接口
* @param message 消息
* @param id sessionId
* @return
*/
@GetMapping("/sendOne")
public String sendOne(@RequestParam String message,@RequestParam String id){
WebSocketServer.SendMessage(id,message);
return "ok";
}
}
消息发送的方法
@ServerEndpoint("/ws/asset")
@Component
public class WebSocketServer {
private static Logger log = LoggerFactory.getLogger(WebSocketServer.class);
public static final AtomicInteger ONLINE_COUNT = new AtomicInteger(0);
/**
* 存放每个客户端对应的session对象
*/
private static CopyOnWriteArraySet<Session> SessionSet = new CopyOnWriteArraySet<>();
@OnOpen
public void onOpen(Session session){
SessionSet.add(session);
int count = ONLINE_COUNT.incrementAndGet();
log.info("有新的连接加入:{},当前连接数为:{}",session.getId(),count);
}
@OnClose
public void OnClose(Session session){
SessionSet.remove(session);
int count = ONLINE_COUNT.decrementAndGet();
log.info("有连接关闭:{},当前连接数为:{}",session.getId(),count);
}
@OnMessage
public void OnMessage(String message,Session session){
log.info("收到客户端消息:{}",message);
sendMessage(session,"浏览器收到消息:"+message);
}
@OnError
public void OnError(Session session,Throwable error){
log.error("发生错误:{},Session ID: {}",error.getMessage(),session.getId());
error.printStackTrace();
}
public static void sendMessage(Session session,String message){
try {
session.getBasicRemote().sendText(String.format("%s (From Server,Session ID=%s)",message,session.getId()));
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public static void broadCastInfo(String message) {
for (Session session : SessionSet) {
if(session.isOpen()){
sendMessage(session,message);
}
}
}
public static void SendMessage(String id, String message) {
Session session = null;
//先通过id找到session
for (Session s : SessionSet) {
if(s.getId().equals(id)){
session = s;
break;
}
}
if(session != null){
sendMessage(session,message);
}else{
log.error("未找到指定的sessionId");
}
}
}
springboot启动类
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
启动服务
访问http://localhost:8080/ws,多开几个页面访问http://localhost:8080/ws,每开一个页面,都能收到服务器定时群发消息
通过调用接口,让服务器群发和单发消息
群发:http://localhost:8080/test/sendAll?message=123
单发:http://localhost:8080/test/sendOne?message=单发消息内容&id=1(这里的id是session Id)