WebSocket 简单入门
websocket 应用场景:社交订阅、多玩家游戏、协同编程/编辑、点击数据流、股票基金报价、体育实况更新、多媒体聊天、基于位置的应用、在线教育等等。
参考:https://blog.csdn.net/resilient/article/details/85613446
online-chatroom 效果图
简单做一下:
前端
socket = new WebSocket('ws://localhost:9999/ws/demo')
socket.onopen = function () {
}
socket.onmessage = function (msg) {
let data = JSON.parse(msg.data)
}
socket.onerror = function () {
alert('onerror, ws 发生了错误')
}
socket.onclose = function () {
console.log('连接已关闭')
}
后端
引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
使用 websocket 依赖提供的 @ServerEndpoint 、 @OnOpen 、@OnClose 、@OnMessage 等注解,结合 WebSocket 生命周期进行业务方法编写。与 socket 编程相似,无非是什么阶段干什么事。
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
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;
@ServerEndpoint(value = "/ws/{username}")
@Component
public class WebSocketServer {
public static final Map<String, Session> SESSION_MAP = new ConcurrentHashMap<>();
private static final Logger log = LoggerFactory.getLogger(WebSocketServer.class);
@OnOpen
public void onOpen(Session session, @PathParam("username") String username) {
if (username == null || "".equals(username) || SESSION_MAP.containsKey(username)) {
log.info("重复加入,或用户名无效,当前用户已加入 {}", username);
try {
JSONObject jsonObject = new JSONObject();
jsonObject.set("msg", "username不合法");
sendMessage(jsonObject.toString(), session);
session.close();
} catch (IOException e) {
log.error("关闭失败", e);
}
return;
}
SESSION_MAP.put(username, session);
log.info("新增会话,用户[{}], 当前在线人数为:{}", username, SESSION_MAP.size());
JSONObject result = new JSONObject();
JSONArray array = new JSONArray();
for (Object key : SESSION_MAP.keySet()) {
JSONObject jsonObject = new JSONObject();
jsonObject.set("username", key);
array.add(jsonObject);
}
result.set("users", array);
sendMsg2All(JSONUtil.toJsonStr(result));
}
@OnClose
public void onClose(Session session, @PathParam("username") String username) {
SESSION_MAP.remove(username);
log.info("连接关闭,移除[{}]的用户会话, 当前在线人数为={}", username, SESSION_MAP.size());
}
@OnMessage
public void onMessage(String message, Session session, @PathParam("username") String username) {
log.info("收到消息,来自[{}]的消息[{}]", username, message);
JSONObject obj = JSONUtil.parseObj(message);
String toUsername = obj.getStr("to");
String text = obj.getStr("text");
Session toSession = SESSION_MAP.get(toUsername);
if (toSession != null) {
JSONObject jsonObject = new JSONObject();
jsonObject.set("from", username);
jsonObject.set("text", text);
this.sendMessage(jsonObject.toString(), toSession);
log.info("发送消息成功:[{}]成功给[{}]发送消息[{}]", username, toUsername, jsonObject);
} else {
log.info("发送失败,未找到用户[{}]的会话", toUsername);
}
}
@OnError
public void onError(Session session, Throwable error) {
log.error("发生错误, sessionId = {}", session.getId());
error.printStackTrace();
}
private void sendMessage(String message, Session toSession) {
try {
toSession.getBasicRemote().sendText(message);
log.info("成功发送[{}]消息给客户端(sessionId={})", message, toSession.getId());
} catch (Exception e) {
log.error("发送消息失败", e);
}
}
private void sendMsg2All(String message) {
try {
for (Session session : SESSION_MAP.values()) {
try {
session.getBasicRemote().sendText(message);
log.info("服务端成功发送消息[{}]给客户端[{}]", message, session.getId());
} catch (Exception e) {
log.error("发送消息失败", e);
}
}
} catch (Exception e) {
log.error("发送消息失败", e);
}
}
}
源代码
完整代码:https://gitee.com/engureguo/websocket-demo
参考
https://blog.csdn.net/xqnode/article/details/124360506
|