Socket.IO

624 阅读2分钟

介绍

什么是 Socket.IO

Socket.IO 是一个库,可以在客户端和服务器之间实现 低延迟双向 和 基于事件的 通信。

Diagram of a communication between a server and a client

它建立在 WebSocket 协议之上,并提供额外的保证,例如回退到 HTTP 长轮询或自动重新连接。下面是Java版的基本示例:

示例

maven依赖

<!-- socketio -->
<dependency>
    <groupId>com.corundumstudio.socketio</groupId>
    <artifactId>netty-socketio</artifactId>
    <version>1.7.7</version>
</dependency>

配置文件

#监听的ip(部署后设置为0.0.0.0)
socketIo.host=127.0.0.1
#监听端口
socketIo.port=10246
# 设置最大每帧处理数据的长度,防止他人利用大数据来攻击服务器
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

配置类

import com.corundumstudio.socketio.SocketConfig;
import com.corundumstudio.socketio.SocketIOServer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
​
@Configuration
public class SocketIoConfig {
    
    @Value("${socketIo.host}")
    private String host;
​
    @Value("${socketIo.port}")
    private Integer port;
​
    @Value("${socketIo.bossCount}")
    private int bossCount;
​
    @Value("${socketIo.workCount}")
    private int workCount;
​
    @Value("${socketIo.allowCustomRequests}")
    private boolean allowCustomRequests;
​
    @Value("${socketIo.upgradeTimeout}")
    private int upgradeTimeout;
​
    @Value("${socketIo.pingTimeout}")
    private int pingTimeout;
​
    @Value("${socketIo.pingInterval}")
    private int pingInterval;
​
    /**
     * 以下配置在上面的application.properties中已经注明
     *
     * @return
     */
    @Bean
    public SocketIOServer socketIOServer() {
        SocketConfig socketConfig = new SocketConfig();
        socketConfig.setTcpNoDelay(true);
        socketConfig.setSoLinger(0);
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        config.setSocketConfig(socketConfig);
        config.setHostname(host);
        config.setPort(port);
        config.setBossThreads(bossCount);
        config.setWorkerThreads(workCount);
        config.setAllowCustomRequests(allowCustomRequests);
        config.setUpgradeTimeout(upgradeTimeout);
        config.setPingTimeout(pingTimeout);
        config.setPingInterval(pingInterval);
        return new SocketIOServer(config);
    }
}

SocketIoService

import com.alibaba.fastjson.JSONObject;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
​
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
​
@Slf4j
@Component
public class SocketIoService {
​
    /**
     * 用来存已连接的客户端
     */
    private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();
​
    @Resource
    private SocketIOServer socketIOServer;
​
    /**
     * Spring IoC容器创建之后,在加载SocketIOServiceImpl Bean之后启动
     *
     * @throws Exception
     */
    @PostConstruct
    private void autoStartup() {
        start();
    }
​
    /**
     * Spring IoC容器在销毁SocketIOServiceImpl Bean之前关闭,避免重启项目服务端口占用问题
     *
     * @throws Exception
     */
    @PreDestroy
    private void autoStop() {
        stop();
    }
​
    public void start() {
        // 监听客户端连接
        socketIOServer.addConnectListener(client -> {
            String uid = getParamsByClient(client);
            if (uid != null) {
                clientMap.put(uid, client);
                log.info("有新的客户端连接UID:{}", uid);
            }
        });
​
        // 监听客户端断开连接
        socketIOServer.addDisconnectListener(listener -> {
            String uid = getParamsByClient(listener);
            if (uid != null) {
                clientMap.remove(uid);
                listener.disconnect();
                log.info("一条客户端连接中断");
            }
        });
​
        socketIOServer.addEventListener("ServerReceive", JSONObject.class, (client, data, ackSender) -> {
            String uid = getParamsByClient(client);
            if (uid != null) {
                log.info("接收到SID:{}发来的消息:{}", uid, data.toJSONString());
            }
        });
​
        socketIOServer.start();
        log.info("socket.io初始化服务完成");
    }
​
    public void stop() {
        if (socketIOServer != null) {
            socketIOServer.stop();
            socketIOServer = null;
        }
        log.info("socket.io服务已关闭");
    }
​
    /**
     * 此方法为获取client连接中的参数,可根据需求更改
     *
     * @param client
     * @return
     */
    private String getParamsByClient(SocketIOClient client) {
        // 从请求的连接中拿出参数(这里的sid必须是唯一标识)
        Map<String, List<String>> params = client.getHandshakeData().getUrlParams();
        List<String> list = params.get("UID");
        if (list != null && list.size() > 0) {
            return list.get(0);
        }
        return null;
    }
​
    /**
     * 推送告警信息
     *
     * @param jsonObject 告警信息
     */
    public static void sendInfo(JSONObject jsonObject) {
        for (SocketIOClient client : clientMap.values()){
            client.sendEvent("alarmInfo",jsonObject);
        }
    }
}

前端代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
</head>
<body>
</body>
<script src="socket.io.js"></script>
<script type="text/javascript">
    const serverUri = "http://127.0.0.1:10246/";
    const sendEvent = "ServerReceive";
    const receiveEvent = "alarmInfo";
​
    var socket;
​
    connect(uuid());
​
    function connect(uid) {
        socket = io.connect(serverUri, {
            'force new connection': true,
            'query': 'UID=' + uid
        });
        socket.on('connect', function () {
            console.log("连接成功");
            // 如果发送字符串send("hello Server"); *需要修改服务端接收类型
             send({
                 name: "client",
                 message: "hello Server"
            });
        });
        socket.on(receiveEvent, function (data) {
            console.log(data);
        });
        socket.on('disconnect', function () {
            console.log("连接断开");
        });
​
    }
​
    function send(data) {
        socket.emit(sendEvent, data);
    }
    function uuid() {
        var s = [];
        var hexDigits = "0123456789abcdef";
        for (var i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4";
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
        s[8] = s[13] = s[18] = s[23] = "-";
​
        var uuid = s.join("");
        return uuid;
    }
</script>
</html>