Netty-SocketIO(2.0.3)+scoket-io-client(4.7.6)实时聊天
一、后端
参考https://www.jianshu.com/p/c67853e729e2
1、引入依赖
版本这里有个大坑,2.0.3能和scoket-io-client(4版本)通信,但是2.0.2就不行,注意2.0.3版本以上鉴权方法有变化
<dependency> <groupId>com.corundumstudio.socketio</groupId> <artifactId>netty-socketio</artifactId> <version>2.0.3</version> </dependency>
2、application.properties相关配置
# host在本地测试可以设置为localhost或者本机IP,在Linux服务器跑可换成服务器IP socketio.host=localhost socketio.port=9099 # 设置最大每帧处理数据的长度,防止他人利用大数据来攻击服务器 socketio.maxFramePayloadLength=1048576 # 设置http交互最大内容长度 socketio.maxHttpContentLength=1048576 # socket连接数大小(如只监听一个端口boss线程组为1即可) socketio.bossCount=1 socketio.workCount=100 socketio.allowCustomRequests=true # 协议升级超时时间(毫秒),默认10秒。HTTP握手升级为ws协议超时时间 socketio.upgradeTimeout=1000000 # Ping消息超时时间(毫秒),默认60秒,这个时间间隔内没有接收到心跳消息就会发送超时事件 socketio.pingTimeout=6000000 # Ping消息间隔(毫秒),默认25秒。客户端向服务器发送一条心跳消息间隔 socketio.pingInterval=25000
3、SocketIOConfig.java配置文件相关配置
1 package com.ruoyi.live.socketIo; 2 3 import cn.dev33.satoken.stp.StpUtil; 4 import com.corundumstudio.socketio.AuthorizationListener; 5 import com.corundumstudio.socketio.HandshakeData; 6 import com.corundumstudio.socketio.SocketConfig; 7 import com.corundumstudio.socketio.SocketIOServer; 8 import com.ruoyi.common.utils.StringUtils; 9 import org.springframework.beans.factory.annotation.Value; 10 import org.springframework.context.annotation.Bean; 11 import org.springframework.context.annotation.Configuration; 12 13 @Configuration 14 public class SocketIOConfig { 15 16 @Value("${socketio.host}") 17 private String host; 18 19 @Value("${socketio.port}") 20 private Integer port; 21 22 @Value("${socketio.bossCount}") 23 private int bossCount; 24 25 @Value("${socketio.workCount}") 26 private int workCount; 27 28 @Value("${socketio.allowCustomRequests}") 29 private boolean allowCustomRequests; 30 31 @Value("${socketio.upgradeTimeout}") 32 private int upgradeTimeout; 33 34 @Value("${socketio.pingTimeout}") 35 private int pingTimeout; 36 37 @Value("${socketio.pingInterval}") 38 private int pingInterval; 39 40 //@Value("${socketio.namespace}") 41 //private String namespace; 42 43 /** 44 * 以下配置在上面的application.properties中已经注明 45 * @return 46 */ 47 @Bean 48 public SocketIOServer socketIOServer() { 49 SocketConfig socketConfig = new SocketConfig(); 50 socketConfig.setTcpNoDelay(true); 51 socketConfig.setSoLinger(0); 52 com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration(); 53 config.setSocketConfig(socketConfig); 54 config.setHostname(host); 55 config.setPort(port); 56 config.setBossThreads(bossCount); 57 config.setWorkerThreads(workCount); 58 config.setAllowCustomRequests(allowCustomRequests); 59 config.setUpgradeTimeout(upgradeTimeout); 60 config.setPingTimeout(pingTimeout); 61 config.setPingInterval(pingInterval); 62 63 // 鉴权 64 config.setAuthorizationListener(new AuthorizationListener() { 65 66 @Override 67 public boolean isAuthorized(HandshakeData handshakeData) { 68 // 获取socket链接发来的token参数 69 String token = handshakeData.getSingleUrlParam("token"); 70 // 如果验签通过就是true,否则false, false的话就不允许建立socket链接 71 if (StringUtils.isNotEmpty(token) && StpUtil.getLoginIdByToken(token) != null) { 72 return true; 73 } 74 return false; 75 } 76 }); 77 SocketIOServer socketIOServer = new SocketIOServer(config); 78 // 添加命名空间 79 // socketIOServer.addNamespace(namespace); 80 return socketIOServer; 81 } 82 83 }
四、提供SocketIOService接口
public interface SocketIOService { // 启动服务 void start() throws Exception; // 停止服务 void stop(); }
五、具体实现方法
import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import javax.annotation.PostConstruct; import javax.annotation.PreDestroy; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.corundumstudio.socketio.SocketIOClient; import com.corundumstudio.socketio.SocketIOServer; @Service(value = "socketIOService") public class SocketIOServiceImpl implements SocketIOService { // 用来存已连接的客户端 private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>(); @Autowired private SocketIOServer socketIOServer; /** * Spring IoC容器创建之后,在加载SocketIOServiceImpl Bean之后启动 * @throws Exception */ @PostConstruct private void autoStartup() throws Exception { start(); } /** * Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题 * @throws Exception */ @PreDestroy private void autoStop() throws Exception { stop(); } @Override public void start() { // 监听客户端连接 socketIOServer.addConnectListener(client -> { String loginUserNum = getParamsByClient(client); if (loginUserNum != null) { clientMap.put(loginUserNum, client); } }); // 监听客户端断开连接 socketIOServer.addDisconnectListener(client -> { String loginUserNum = getParamsByClient(client); if (loginUserNum != null) { clientMap.remove(loginUserNum); client.disconnect(); } }); // 处理自定义的事件,与连接监听类似,event为事件名,PushMessage为参数实体类
// 监听前端发送的事件 socketIOServer.addEventListener("event", PushMessage.class, (client, data, ackSender) -> { // TODO do something }); socketIOServer.start(); } @Override public void stop() { if (socketIOServer != null) { socketIOServer.stop(); socketIOServer = null; } } public void pushMessageToUser(PushMessage pushMessage) { String loginUserNum = pushMessage.getLoginUserNum(); if (StringUtils.isNotBlank(loginUserNum)) { SocketIOClient client = clientMap.get(loginUserNum); if (client != null)
// 通过sendEvent给前端发送事件,并传递参数 client.sendEvent(PUSH_EVENT, pushMessage); } } /** * 此方法为获取client连接中的参数,可根据需求更改 * @param client * @return */ private String getParamsByClient(SocketIOClient client) { // 从请求的连接中拿出参数(这里的loginUserNum必须是唯一标识) Map<String, List<String>> params = client.getHandshakeData().getUrlParams(); List<String> list = params.get("loginUserNum"); if (list != null && list.size() > 0) { return list.get(0); } return null; } }
二、前端
1、下载
npm install socket.io-client
2、引入
import io from 'socket.io-client';
3、监听连接、自定义事件、退出
mounted { // 连接参数 let opts = new Object(); // 连接scoket服务器,ip为socket地址 var socket = io('ip', opts); // 监听连接后的回调 socket.on('connect', function(){}); // 监听自定义事件,event为事件名,并接受后台传过来的参数 socket.on('event', function(data){}); // 监听退出后的回调函数 socket.on('disconnect', function(){}); }
4、发送事件
// event为事件名,data为参数 socket.emit('event', data);
三、总结
1、前端可以通过socket.on来监听,socket.emit来发送事件。
2、后端可以通过SocketIOClient的sendEvent发送事件,socketIOServer.addDisconnectListener来监听。