其他分享
首页 > 其他分享> > Netty-SocketIO+scoket-io-client实现实时聊天思路

Netty-SocketIO+scoket-io-client实现实时聊天思路

作者:互联网

一、后端

参考https://www.jianshu.com/p/c67853e729e2

1、引入依赖

<dependency>
    <groupId>com.corundumstudio.socketio</groupId>
    <artifactId>netty-socketio</artifactId>
    <version>1.7.7</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 import com.corundumstudio.socketio.SocketConfig;
 2 import org.springframework.beans.factory.annotation.Value;
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.context.annotation.Configuration;
 5 
 6 import com.corundumstudio.socketio.SocketIOServer;
 7 
 8 @Configuration
 9 public class SocketIOConfig {
10 
11     @Value("${socketio.host}")
12     private String host;
13 
14     @Value("${socketio.port}")
15     private Integer port;
16 
17     @Value("${socketio.bossCount}")
18     private int bossCount;
19 
20     @Value("${socketio.workCount}")
21     private int workCount;
22 
23     @Value("${socketio.allowCustomRequests}")
24     private boolean allowCustomRequests;
25 
26     @Value("${socketio.upgradeTimeout}")
27     private int upgradeTimeout;
28 
29     @Value("${socketio.pingTimeout}")
30     private int pingTimeout;
31 
32     @Value("${socketio.pingInterval}")
33     private int pingInterval;
34 
35     /**
36      * 以下配置在上面的application.properties中已经注明
37      * @return
38      */
39     @Bean
40     public SocketIOServer socketIOServer() {
41         SocketConfig socketConfig = new SocketConfig();
42         socketConfig.setTcpNoDelay(true);
43         socketConfig.setSoLinger(0);
44         com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
45         config.setSocketConfig(socketConfig);
46         config.setHostname(host);
47         config.setPort(port);
48         config.setBossThreads(bossCount);
49         config.setWorkerThreads(workCount);
50         config.setAllowCustomRequests(allowCustomRequests);
51         config.setUpgradeTimeout(upgradeTimeout);
52         config.setPingTimeout(pingTimeout);
53         config.setPingInterval(pingInterval);
54         return new SocketIOServer(config);
55     }
56 }

四、提供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来监听。

标签:Netty,scoket,socketio,SocketIO,private,client,import,loginUserNum,config
来源: https://www.cnblogs.com/liuyu666/p/13550125.html