- java端代码
- 前端代码
不废话,上代码,贴了就好使!
java端代码import com.alibaba.fastjson.JSON; import com.zmj.digitalworkshop.panel.dip.angle.entity.Message; import io.swagger.annotations.ApiOperation; 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.Date; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicInteger; @Component @ServerEndpoint("/webSocket/{username}") public class WebSocketServer { private static AtomicInteger onlineNum = new AtomicInteger(); private static ConcurrentHashMap前端代码sessionPools = new ConcurrentHashMap<>(); @OnOpen public void onOpen(Session session, @PathParam(value = "username") String userName) throws IOException, InterruptedException { sessionPools.put(userName, session); // 当前在线人数+1 addOnlineCount(); System.out.println(userName + "加入webSocket!当前人数为" + onlineNum); // 广播上线消息 } @OnClose @ApiOperation(value = "获取当前在线用户数量及列表", notes = "获取当前在线用户数量及列表", httpMethod = "WS") public void onClose(@PathParam(value = "username") String userName) throws IOException { sessionPools.remove(userName); // 当前在线人数-1 subOnlineCount(); System.out.println(userName + "断开webSocket连接!当前人数为" + onlineNum); // 广播下线消息(视需求而用) } public static void sendInfo(String userName, String message){ Session session = sessionPools.get(userName); try { sendMessage(session, message); }catch (Exception e){ e.printStackTrace(); } } public void broadcast(String message){ for (Session session: sessionPools.values()) { try { sendMessage(session, message); } catch(Exception e){ e.printStackTrace(); continue; } } } public static void sendMessage(Session session, String message) throws IOException { if(session != null){ synchronized (session) { System.out.println("发送数据:" + message); session.getBasicRemote().sendText(message); } } } @OnMessage public void onMessage(String message) throws IOException{ System.out.println("server get" + message); Message msg=JSON.parseObject(message, Message.class); msg.setDate(new Date()); if (msg.getType().equals("-1")) { broadcast(JSON.toJSONString(msg,true)); } else { sendInfo(msg.getType(), JSON.toJSONString(msg,true)); } } @OnError public void onError(Session session, Throwable throwable){ System.out.println("发生错误"); throwable.printStackTrace(); } public static void addOnlineCount(){onlineNum.incrementAndGet();} public static void subOnlineCount() {onlineNum.decrementAndGet();} public static AtomicInteger getOnlineNumber() {return onlineNum;} public static ConcurrentHashMap getSessionPools() {return sessionPools;} }
随便写了点大概意思就是这
TOM就是要链接的用户名称
document
要看浏览器 websocket 的数据的话,如下:
谷歌,F12,然后点 WS,就能看到 webSocket 的一些消息了
别看我的报红了,因为我懒,不想开项目,它连不上
要是写的还行的话,给我点动力点个赞吧
有什么问题当前页面请留言。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)