package com.kapark.cloud.socket;import com.kapark.cloud.context.AudioSender;import com.xiaoleilu.hutool.log.Log;import com.xiaoleilu.hutool.log.LogFactory;import org.springframework.stereotype.Component;import javax.websocket.*;import javax.websocket.server.PathParam;import javax.websocket.server.ServerEndpoint;import java.io.IOException;import java.nio.ByteBuffer;import java.util.concurrent.ConcurrentHashMap;/*** @author: hyzhan* @date: 2019年6月14日* @desc: TODO*/@Component@ServerEndpoint("/websocket/{devId}")public class AudioSocket {private static Log log = LogFactory.get(AudioSocket.class);//静态变量,用来记录当前在线连接数。应该把它设计成线程安全的。private static int onlineCount = 0;//concurrent包的线程安全Set,用来存放每个客户端对应的 AudioSocket 对象。private static ConcurrentHashMap<Integer, AudioSocket> webSocketMap = new ConcurrentHashMap<>();//与某个客户端的连接会话,需要通过它来给客户端发送数据private Session session;//接收devIdprivate int devId;/*** 连接建立成功调用的方法*/@OnOpenpublic void onOpen(Session session, @PathParam("devId") int devId) {this.session = session;this.devId = devId;webSocketMap.put(devId, this);addOnlineCount(); //在线数加1log.info("有新窗口开始监听:" + devId + ",当前在线人数为" + getOnlineCount());}/*** 连接关闭调用的方法*/@OnClosepublic void onClose() {webSocketMap.remove(devId, this); //从set中删除subOnlineCount(); //在线数减1log.info("有一连接关闭!当前在线人数为" + getOnlineCount());}/*** 收到客户端消息后调用的方法** @param message 客户端发送过来的消息*/@OnMessagepublic void onMessage(byte[] message, Session session) {log.info("接受byte length: " + message.length);AudioSender.send2Intercom(devId, message);}@OnErrorpublic void onError(Session session, Throwable error) {log.error("发生错误");error.printStackTrace();}/*** 发自定义消息*/public static void send2Client(int devId, byte[] data, int len) {AudioSocket audioSocket = webSocketMap.get(devId);if (audioSocket != null) {try {synchronized (audioSocket.session) {audioSocket.session.getBasicRemote().sendBinary(ByteBuffer.wrap(data, 0, len));}} catch (IOException e) {e.printStackTrace();}}}private static synchronized int getOnlineCount() {return onlineCount;}private static synchronized void addOnlineCount() {AudioSocket.onlineCount++;}private static synchronized void subOnlineCount() {AudioSocket.onlineCount--;}}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。