java使用socket.io进行web实时通讯 netty-socketio

服务端JAVA

  • 创建一个spring boot项目
  • 在pom.xml中加入netty-socketio和fastjson
<dependency>
	<groupId>com.corundumstudio.socketiogroupId>
	<artifactId>netty-socketioartifactId>
	<version>1.7.7version>
dependency>
<dependency>
	<groupId>com.alibabagroupId>
	<artifactId>fastjsonartifactId>
	<version>1.2.4version>
dependency>
  • 在application.yml中加入
#============================================================================
# netty socket io setting
#============================================================================
# host在本地测试可以设置为localhost或者本机IP,在Linux服务器跑可换成服务器IP
socketio:
  host: 127.0.0.1	#监听的ip
  port: 10246		#监听端口
  # 设置最大每帧处理数据的长度,防止他人利用大数据来攻击服务器
  maxFramePayloadLength: 1048576
  # 设置http交互最大内容长度
  maxHttpContentLength: 1048576
  # socket连接数大小(如只监听一个端口boss线程组为1即可)
  bossCount: 1
  workCount: 100
  allowCustomRequests: true
  # 协议升级超时时间(毫秒),默认10秒。HTTP握手升级为ws协议超时时间
  upgradeTimeout: 1000000
  # Ping消息超时时间(毫秒),默认60秒,这个时间间隔内没有接收到心跳消息就会发送超时事件
  pingTimeout: 6000000
  # Ping消息间隔(毫秒),默认25秒。客户端向服务器发送一条心跳消息间隔
  pingInterval: 25000
  • 新建SocketIoConfig
import com.corundumstudio.socketio.SocketConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.corundumstudio.socketio.SocketIOServer;

@Configuration
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);
    }
}
  • 创建Server
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;

@Service
public class SocketIoTest {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // 用来存已连接的客户端
    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();
    }

    public void start() {
        // 监听客户端连接
        socketIOServer.addConnectListener(client -> {
            String uid = getParamsByClient(client);
            if (uid != null) {
                clientMap.put(uid, client);
                logger.info("有新客户端连接UID:{}",uid);
            }
            // 给客户端发送一条信息 发送ClientReceive事件 需要客户端绑定此事件即可接收到消息
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("name","goat");
            jsonObject.put("message","hello client");
            client.sendEvent("ClientReceive",jsonObject);
        });

        // 监听客户端断开连接
        socketIOServer.addDisconnectListener(client -> {
            String uid = getParamsByClient(client);
            if (uid != null) {
                clientMap.remove(uid);
                client.disconnect();
            }
            logger.info("一条客户端连接中断");
        });

        // 处理自定义的事件,与连接监听类似
        // 此示例中测试的json收发 所以接收参数为JSONObject 如果是字符类型可以用String.class或者Object.class
        socketIOServer.addEventListener("ServerReceive",JSONObject.class, (client, data, ackSender) -> {
            // TODO do something
            JSONObject jsonObject = data;
            String uid = getParamsByClient(client);
            if (uid != null) {
                logger.info("接收到SID:{}发来的消息:{}",uid,jsonObject.toJSONString());
            }
        });
        socketIOServer.start();
        logger.info("socket.io初始化服务完成");
    }

    public void stop() {
        if (socketIOServer != null) {
            socketIOServer.stop();
            socketIOServer = null;
        }
        logger.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;
    }
}
  • 因为加了@Service 可以通过测试启动 加一个System.in.read(); 服务端就结束了。

客户端JS

  • 在页面引入socket.io.js文件 可以自行搜索下载
const serverUri = "http://127.0.0.1:10246";
const sendEvent = "ServerReceive";
const receiveEvent = "ClientReceive";

var socket;

connect(1001);

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);
}

如果操作正确可以看到双方已经开始通讯了

你可能感兴趣的:(WebSocket)