netty-socketio私聊群聊,spring boot版本

一个简单的消息推送例子;

netty-socketio私聊群聊,spring boot版本_第1张图片

Netty-socketio示例

 

2019-10-16 19:6:36 全员消息--12:

2019-10-16 19:6:36 全员消息--12:

2019-10-16 19:6:35 全员消息--12: 速度速度

2019-10-16 19:6:30 成功连接到服务端!

 

html代码:




NettySocket客户端


    


    

Netty-socketio示例


用户: 内容:

java代码:

package com.lambert.socket;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Component;

import com.corundumstudio.socketio.AckRequest;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.annotation.OnConnect;
import com.corundumstudio.socketio.annotation.OnDisconnect;
import com.corundumstudio.socketio.annotation.OnEvent;

@Component
public class EventListenner {
	@Resource
	private ClientCache clientCache;
	@Resource
	private SocketIOService socketIOService;

	/**
	 * 客户端连接
	 * 
	 * @param client
	 */
	@OnConnect
	public void onConnect(SocketIOClient client) {
		String userId = socketIOService.getParamsByClient(client);
		UUID sessionId = client.getSessionId();
		clientCache.saveClient(userId, sessionId, client);
		client.sendEvent("chatevent", userId);
		System.out.println("建立连接");
	}

	/**
	 * 客户端断开
	 * 
	 * @param client
	 */
	@OnDisconnect
	public void onDisconnect(SocketIOClient client) {
		String userId = client.getHandshakeData().getSingleUrlParam("userId");
		clientCache.deleteSessionClient(userId, client.getSessionId());
		System.out.println("关闭连接");
	}

	// 消息接收入口,当接收到消息后,查找发送目标客户端,并且向该客户端发送消息,且给自己发送消息
	@OnEvent("privateEvent")
	public void onPrivateEvent(SocketIOClient client, AckRequest request, PushMessage clientObj) {
		String userId = socketIOService.getParamsByClient(client);
		clientObj.setFromUserId(userId);
		socketIOService.pushMessageToUser(clientObj);
	}

	// 消息接收入口,当接收到消息后,查找发送目标客户端,并且向该客户端发送消息,且给自己发送消息
	@OnEvent("publicEvent")
	public void onPublicEvent(SocketIOClient client, AckRequest request, PushMessage clientObj) {
		String userId = socketIOService.getParamsByClient(client);
		clientObj.setFromUserId(userId);
		Map> map = clientCache.getUserClient();
		for (HashMap hmap : map.values()) {
			for (SocketIOClient socketIOClient : hmap.values()) {
				socketIOClient.sendEvent(SocketIOService.PUSH_PUBLIC_EVENT, clientObj);
			}
		}

	}
}

代码下载地址:

https://gitee.com/lamber/Netty-SocketIO.git

你可能感兴趣的:(Java)