如果是初次搭建Spring Boot+WebSocket项目,不需要太复杂,只需要快速上手,那么你搜到的大部分文章可能都不适合你,我的这篇文章以最精简的方式搭建一个可以运行并通信的Spring Boot+WebSocket的Demo项目,有了根基之后再进行复杂化就不是难事了。

第一步:搭建一个Spring Boot项目

搭建Spring Boot项目都会吧,下面展示pom.xml文件中重要的依赖。

org.springframework.boot

spring-boot-starter-parent

2.2.6.RELEASE

org.springframework.boot

spring-boot-starter-websocket

第二步:WebSocket配置类

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.web.socket.server.standard.ServerEndpointExporter;

@Configuration

public class WebSocketConfig {

@Bean

public ServerEndpointExporter serverEndpointExporter() {

return new ServerEndpointExporter();

}

}

第三步:WebSocket通信服务

import org.apache.tomcat.websocket.WsSession;

import org.springframework.stereotype.Service;

import javax.websocket.*;

import javax.websocket.server.PathParam;

import javax.websocket.server.ServerEndpoint;

import java.io.IOException;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

@Service

@ServerEndpoint("/myws/{username}")

public class WebSocketServer {

private static Map sessions = new ConcurrentHashMap<>();

@OnOpen

public void onOpen(Session session, @PathParam("username") String username){

System.out.println("有新的连接进来了:"+username);

sessions.put(username,(WsSession) session);

}

@OnMessage

public void onMessage(Session session, @PathParam("username") String username,String msg){

System.out.println(username+":发送消息");

for (WsSession wsSession : sessions.values()) {

if(wsSession.isOpen()){

try {

wsSession.getBasicRemote().sendText(msg);

} catch (IOException e) {

e.printStackTrace();

}

}

}

}

@OnClose

public void onClose(Session session, @PathParam("username") String username){

System.out.println(username+":关闭连接");

}

@OnError

public void onError(Session session,@PathParam("username") String username,Throwable throwable){

System.out.println("发生错误");

throwable.printStackTrace();

}

}

第四步:前端页面

Title

第五步:运行测试

参考阅读

评论可见,请评论后查看内容,谢谢!!!
 您阅读本篇文章共花了: 


大家都在找:

spring boot:springboot配置文件

websocket:websocket 测试

Java:java我的世界

大家都在看: