首先,现在配置文件pom中导入需要的依赖包
org.springframework.boot spring-boot-starter-websocketorg.springframework.boot spring-boot-starter-testtest
创建文件websocketconfig,创建bean
@Configuration
public class MyWebSocketConfig {
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
}
创建websocketserver
@Component
//主要是将目前的类定义成一个websocket服务器端, 注解的值将被用于监听用户连接的终端访问URL地址,客户端可以通过这个URL来连接到WebSocket服务器端
@ServerEndpoint(value = "/websocket/{userName}")
//此注解相当于设置访问URL
public class WebSocketServer {
private Session session;
private String userName;
private static int onlineCount = 0;
private static CopyOnWriteArraySet webSockets =new CopyOnWriteArraySet<>();
private static Map sessionPool = new HashMap();
@OnOpen
public void onOpen(Session session, @PathParam(value="userName")String userName) {
this.session = session;
webSockets.add(this);
sessionPool.put(userName, session);
Session res = sessionPool.get(userName);
System.out.println(userName+"【websocket消息】有新的连接,总数为:"+webSockets.size());
}
@OnClose
public void onClose() {
webSockets.remove(this);
System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
}
@OnError
public void onError(Session session, Throwable error) {
System.out.println("[连接ID:{}] 错误原因:{}" + this.session + error.getMessage());
}
@OnMessage
public void onMessage(String message) {
System.out.println("【websocket消息】收到客户端消息:"+message);
}
// 此为广播消息
public void sendAllMessage(String message) {
for(WebSocketServer webSocket : webSockets) {
System.out.println("【websocket消息】广播消息:"+message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
// 此为单点消息
public void sendOneMessage(String userName, String message) {
System.out.println("【websocket消息】单点消息:"+message);
System.out.println(sessionPool);
Session session = sessionPool.get(userName);
if (session != null) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
websocket用来编写接口
@RestController
@RequestMapping("/test")
public class websocket {
@Autowired
private WebSocketServer webSocketServer;
@GetMapping("/sendAllWebSocket")
public String test() {
String text="你们好!这是websocket群体发送!";
webSocketServer.sendAllMessage(text);
return text;
}
@GetMapping("/sendOneWebSocket/{userName}")
public String sendOneWebSocket(@PathVariable("userName") String userName) {
String text=userName+" 你好! 这是websocket单人发送!";
webSocketServer.sendOneMessage(userName,text);
return text;
}
}
vue部分
created() {
this.initWebSocket();
},
destroyed() {
this.websock.close();//离开路由之后断开websocket连接
},
methods: {
initWebSocket(){//初始化weosocket(必须)
let name = localStorage.getItem("userName",this.username)
let socket = "ws://127.0.0.1:8080/websocket/" + name
const wsuri = socket; //请根据实际项目需要进行修改
this.websock = new WebSocket(wsuri); //新建一个webstock对象
this.websock.onmessage = this.websocketonmessage;
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onclose = this.websocketclose;
},
websocketonopen(){//websocket连接后发送数据(send发送)
let actions = this.message; //请根据实际项目需要进行修改
this.websocketsend(JSON.stringify(actions));
},
websocketonerror(){//连接建立失败重连
this.initWebSocket();
},
websocketonmessage(e){ //数据接收
console.log(e.data);
this.redata.push(e.data)
// this.redata = eval(e.data);
// console.log(this.redata);
},
websocketsend(Data){//数据发送
this.websock.send(Data);
},
websocketclose(e){ //关闭
console.log('断开连接',e);
},
},



