WebSocket简单使用
后端:
加入依赖:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
<version>2.0.4.RELEASE</version>
</dependency>
创建一个配置类:
@Bean
public ServerEndpointExporter serverEndpointExporter() {
return new ServerEndpointExporter();
}
controller层:
@RestController
@RequestMapping("/websocket")
public class TestController {
@Autowired
private WebSocket webSocket;
@RequestMapping("/sendAllWebSocket")
public String test(@RequestBody Map map) {
webSocket.sendAllMessage((String) map.get("message"));
return "websocket群体发送!";
}
@RequestMapping("/sendOneWebSocket")
public String sendOneWebSocket() {
webSocket.sendOneMessage("", "");
return "websocket单人发送";
}
}
创建一个ws包:
@Component
@ServerEndpoint("/websocket/{id}/{name}")
public class WebSocket {
private Session session;
private static CopyOnWriteArraySet<WebSocket> webSockets =new CopyOnWriteArraySet<>();
private static Map<String,Session> sessionPool = new HashMap<String,Session>();
@OnOpen
public void onOpen(Session session, @PathParam(value="id")String shopId,@PathParam("name")String name) {
this.session = session;
webSockets.add(this);
sessionPool.put(shopId, session);
System.out.println("【websocket消息】有新的连接,总数为:"+webSockets.size());
sendAllMessage(name+": 进入直播间");
}
@OnClose
public void onClose() {
webSockets.remove(this);
System.out.println("【websocket消息】连接断开,总数为:"+webSockets.size());
}
@OnMessage
public void onMessage(String message) {
System.out.println("【websocket消息】收到客户端消息:"+message);
}
public void sendAllMessage(String message) {
for(WebSocket webSocket : webSockets) {
System.out.println("【websocket消息】广播消息:"+message);
try {
webSocket.session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void sendOneMessage(String id, String message) {
Session session = sessionPool.get(id);
if (session != null) {
try {
session.getAsyncRemote().sendText(message);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
前端:
export default {
created() {
this.initWebSocket()
},
destroyed: function () {
this.websocketclose();
},
methods:{
initWebSocket: function () {
var n = Math.floor(Math.random() * (100000 - 0) + 0)
var name = "风雪";
if (this.user.username != null){
this.websock = new WebSocket("ws://localhost:8084/websocket/DPS" + n + "/" + this.user.username);
this.websock.onopen = this.websocketonopen;
this.websock.onerror = this.websocketonerror;
this.websock.onmessage = this.websocketonmessage;
this.websock.onclose = this.websocketclose;
}
},
websocketonopen: function () {
console.log("WebSocket连接成功");
},
websocketonerror: function (e) {
console.log("WebSocket连接发生错误");
},
websocketonmessage: function (e) {
console.log(e.data);
this.addToList(e.data)
this.list.push({
name:'',
message: e.data
})
console.log(this.list)
},
websocketclose: function (e) {
console.log("connection closed (" + e + ")");
},
}
}