SpringBoot基于Socket.IO 聊天室实现

一、前言

本demo为学习SpringBoot搭建SocketIo 使用。部分代码不够规范严谨,代码结构并不好,毕竟在回执消息以及消息体结构的定义、代码的结构等方面都很多改进地方。本想好好梳理,可惜那该死的惰性,真香。故本demo如果使用最好仅仅作为技术实现的小参考,不建议作为开发过程代码使用(况且虽然功能实现了,但是部分代码笔者并不能确定这样写的正确性)。
另外,全发和私发功能实现,群发功能前端没有实现,因为没有选择roomId,毕竟懒癌犯了。。。。。。。

二、Socket.Io后台搭建

搭建SpringBoot框架的部分不在本文范围内,有需要可以自行百度。

1. 引入socket.io依赖

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

2. 新建配置文件 socket.properties, 用于socket.io的配置,其实也可以跳过这一步直接写
在这里插入图片描述
内容如下

# socketio
socketio.port=9096
socketio.upgradeTimeout=3000
socketio.pingInterval=25000
socketio.pingTimeout=8000

3. 创建SocketIoServerConfig 配置类

import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.SpringAnnotationScanner;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

/**
 * @Data: 2019/7/10
 * @Des: SocketIo 配置
 */
@Configuration	// 标志这个类是Spring的一个配置类
@PropertySource(value = "classpath:socket.properties")	// 引入配置文件
public class SocketIoServerConfig {
    @Value("${socketio.port}")
    private int port;
    @Value("${socketio.upgradeTimeout}")
    private int upgradeTimeout;
    @Value("${socketio.pingInterval}")
    private int pingInterval;
    @Value("${socketio.pingTimeout}")
    private int pingTimeout;

    /**
     *  注册一个SocketIoServer bean,
     *  初始化好一切参数,在注入的时候可以不用再初始化
     * @return
     */
    @Bean
    public SocketIOServer socketIoServer(){
       /*
         * 创建Socket,并设置监听端口
         */
        com.corundumstudio.socketio.Configuration config = new com.corundumstudio.socketio.Configuration();
        // 设置主机名,默认是0.0.0.0
        //  config.setHostname("localhost");
        // 设置监听端口
        config.setPort(port);
        // 协议升级超时时间(毫秒),默认10000。HTTP握手升级为ws协议超时时间
        config.setUpgradeTimeout(upgradeTimeout);
        // Ping消息间隔(毫秒),默认25000。客户端向服务器发送一条心跳消息间隔
        config.setPingInterval(pingInterval);
        // Ping消息超时时间(毫秒),默认60000,这个时间间隔内没有接收到心跳消息就会发送超时事件
        config.setPingTimeout(pingTimeout);
        // sessionId是否随机
        config.setRandomSession(true);

        final SocketIOServer server = new SocketIOServer(config);

        return server;
    }

    /**
     * 注入OnConnect,OnDisconnect,OnEvent注解。 不写的话Spring无法扫描OnConnect,OnDisconnect等注解
     * @param socketServer
     * @return
     */
    @Bean
    public SpringAnnotationScanner springAnnotationScanner(SocketIOServer socketServer) {
        return new SpringAnnotationScanner(socketServer);
    }

}

4. 设置SocketIO启动类

// 实现CommandLineRunner接口代表在Spring启动后服务就跟着启动。Order则表示注入优先级为1,即注入的顺序靠前,优先级高
@Component	// 让Spring将其添加为一个可注入的组件
@Order(1)		
public class SocketioServerRunner implements CommandLineRunner {
    private final SocketIOServer server;
    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    public SocketioServerRunner(SocketIOServer server) {
        this.server = server;
    }

    @Override
    public void run(String... args) throws Exception {
    	// spring服务启动后会紧接着启动run方法,即会吊起来socket服务。
        logger.info("ServerRunner 开始启动啦...");
        server.start();
    }
}

5. Socket业务实现类

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.BroadcastAckCallback;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.SocketIOServer;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;
import com.kingfish.pojo.socket.SocketMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @Data: 2019/7/10
 * @Des: SocketIO事件接收
 */
@Component
public class MessageEventhandler {
    private final Logger logger = LoggerFactory.getLogger(getClass());
    private final String DEFAULT_ROOM_ID = "123";


    @Autowired
    private SocketIOServer server;

    private static Map<String, SocketIOClient> clientMap;

    static {
        clientMap = new ConcurrentHashMap<>();
    }

    @OnConnect
    public void onConnect(SocketIOClient client) {
        String clientName = client.getHandshakeData().getSingleUrlParam("clientName");
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        // 这里使用clientName作为key不合适,仅仅作为Demo展示
        clientMap.put(clientName, client);
        SocketMsg socketMsg = new SocketMsg();
        socketMsg.setMessage(clientName + "上线了 ");
        socketMsg.setData(clientMap.keySet());

        // 如果roomId 不为空,则加入指定的房间编号, 并通知指定房间的人上线信息
        if (roomId != null) {
            client.joinRoom(roomId);
            server.getRoomOperations("1").sendEvent("onlineMessage", socketMsg);
        } else {
            // 否则的话通知所有人
            server.getBroadcastOperations().sendEvent("onlineMessage", socketMsg);
        }
        logger.info(clientName + "连接上了 ");
    }

    @OnDisconnect
    public void onDisconnect(SocketIOClient client) {
        String clientName = client.getHandshakeData().getSingleUrlParam("clientName");
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        client.disconnect();
        clientMap.remove(clientName);

        SocketMsg socketMsg = new SocketMsg();
        socketMsg.setMessage(clientName + "下线了 ");
        socketMsg.setData(clientMap.keySet());
        if (roomId != null) {
            client.joinRoom(roomId);
            server.getRoomOperations("1").sendEvent("onlineMessage", socketMsg);
        } else {
            // 否则的话通知所有人
            server.getBroadcastOperations().sendEvent("onlineMessage", socketMsg);
        }
        logger.info(clientName + "断开连接 " + client.getSessionId());
    }

    /**
     * 发送所有人信息
     *
     * @param client
     * @param msg
     */
    @OnEvent(value = "sendMessage")
    public void onSendMessage(SocketIOClient client, SocketMsg msg) {
        server.getBroadcastOperations().sendEvent("receiveMessage", msg.getMessage(), new BroadcastAckCallback<String>(String.class, 5000) {
            @Override
            protected void onAllSuccess() {
                logger.info("全部应答:" + msg);
            }

            @Override
            protected void onClientTimeout(SocketIOClient client) {
                logger.info("应答超时:" + client.getSessionId().toString());
            }
        });
    }

    /**
     * 发送所有人信息
     *
     * @param client
     * @param msg
     * @param ackSender
     */
    @OnEvent(value = "sendOneMessage")
    public void sendOneMessage(SocketIOClient client, SocketMsg msg, AckRequest ackSender) {

        String clientName = msg.getCode();
        if (clientMap.containsKey(clientName)) {
            clientMap.get(clientName).sendEvent("receiveMessage", msg.getMessage());
        } else {
            if (ackSender.isAckRequested()) {
                ackSender.sendAckData("查无此人");
            }
        }

    }

    /**
     * 发送群聊信息
     *
     * @param client
     * @param msg
     * @param ackSender
     */
    @OnEvent(value = "sendRoomMessage")
    public void sendRoomMessage(SocketIOClient client, SocketMsg msg, AckRequest ackSender) {
        String roomId = client.getHandshakeData().getSingleUrlParam("roomId");
        if (client.getAllRooms().contains(roomId)) {
            server.getRoomOperations(roomId).sendEvent("receiveMessage", msg.getMessage(), new BroadcastAckCallback<Object>(Object.class, 5000) {
                @Override
                protected void onAllSuccess() {
                    logger.info("全部应答:" + msg);
                }

                @Override
                protected void onClientTimeout(SocketIOClient client) {
                    logger.info("应答超时:" + client.getSessionId().toString());
                }
            });
        } else {
            // 如果需要回执,则回执错误信息
            if (ackSender.isAckRequested()) {
                ackSender.sendAckData("roomId有错误");
            }
        }
    }

    // spring Ioc 容器销毁前停止服务
    @PreDestroy
    public void stop() {
        if (server != null) {
            server.stop();
        }
    }
}

6. SocketMsg消息类

import java.io.Serializable;

/**
 * @Data : 2019/7/11
 * @Des : Socket消息体
 */
public class SocketMsg<T> implements Serializable {
    private static final long serialVersionUID = -569315342607629651L;
    private String code;
    private String message;
    private T data;

    @Override
    public String toString() {
        return "{" +
                "code:" + code +
                ", message:'" + message + '\'' +
                ", data:" + data +
                '}';
    }

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }
}

三、 前端代码实现

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8" />
		<title>Demo Chat</title>
		<link href="bootstrap.css" rel="stylesheet">
		<style>
			body {
				padding: 20px;
			}
			
			#console {
				height: 400px;
				overflow: auto;
			}
			
			.username-msg {
				color: orange;
			}
			
			.connect-msg {
				color: green;
			}
			
			.disconnect-msg {
				color: red;
			}
			
			.send-msg {
				color: #888
			}
			
			.ack-msg {
				color: blue;
			}
			
			.user {
				color: crimson;
			}
		</style>
		<script src="js/socket.io/socket.io.js"></script>
		<script src="js/moment.min.js"></script>
		<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>

		<script>
			var userName = 'user' + Math.floor((Math.random() * 1000) + 1);
			// 传递参数
			var opts = {
				query: 'clientName=' + userName
			};

			var socket = io.connect('http://localhost:9096', opts);

			// 监听连接事件
			socket.on('connect', function(data) {

			});

			// 监听断开事件
			socket.on('disconnect', function(data) {
				output('<span class="disconnect-msg">已断开服务,用户名为: ' + data + '服务已断开</span>');
			});

			// 监听sendMessage 事件
			socket.on('receiveMessage', function(data, ackServerCallback) {
				output('<span class="username-msg">已收到信息: ' + data + ':</span> ');

			});
			// 监听客户端上线下线事件
			socket.on('onlineMessage', function(message, ackServerCallback) {
				if(message) {
					$("#online option").remove();
					$("#online").prepend("<option value='0'>请选择</option>"); //添加第一个option值
					for(var i = 0; i < message.data.length; i++) {
						$("#online").append("<option value=" + message.data[i] + ">" + message.data[i] + "</option>");
					}
					output('<span class="connect-msg">已连接服务,用户名为: ' + message.message + '</span>');
				}

			});

			function sendDisconnect() {
				socket.disconnect();
			}

			function sendMessage(messageFun) {
				var message = $('#msg').val();
				$('#msg').val('');

				var jsonObject = {
					code: $("#online option:selected").val(),
					data: {
						name: userName, 
						message: message
					},
					message: message
				};

				// 向服务端发送消息
				socket.emit(messageFun, jsonObject, function(result) {
					output('<span class="ack-msg"> 这是回执结果 ' + result + ':</span> ');
				});
				
				socket.send()
			}


			function output(message) {
				var currentTime = "<span class='user'>" + userName + "</span> <span class='time'>" + moment().format('HH:mm:ss.SSS') + "</span>";
				var element = $("<div>" + currentTime + " " + message + "</div>");
				$('#console').append(element);

			}

			$(document).keydown(function(e) {
				if(e.keyCode == 13) {
					$('#send').click();
				}
			});
		</script>
	</head>

	<body>

		<h1>Netty-socketio Demo Chat</h1>

		<div id="console" class="well">
		</div>

		<form class="well form-inline" onsubmit="return false;">
			<input id="msg" class="input-xlarge" type="text" placeholder="Type something..." /> To
			<select id="online" class="search-query">
				<option value='0'>请选择</option>
			</select>
			<button type="button" onClick="sendMessage('sendOneMessage')" class="btn">私发</button>
			<button type="button" onClick="sendMessage('sendRoomMessage')" class="btn">群发</button>
			<button type="button" onClick="sendMessage('sendMessage')" class="btn">全发</button>
		</form>

	</body>

</html>

全发效果图

在这里插入图片描述

私发效果图
在这里插入图片描述


以下:部分内容参考
https://github.com/mrniko/netty-socketio-demo
https://www.jianshu.com/p/4e80b931cdea
如有侵扰,联系删除。 内容仅用于自我记录学习使用。如有错误,欢迎指正。

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猫吻鱼

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值