基于netty-socketio实现消息推送、聊天功能
首先pom中引入netty-socketio
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.11</version>
</dependency>
然后配置socketio的各种参数
# host在本地测试可以设置为localhost或者本机IP
socketio.host=localhost
# 在Linux服务器跑可换成服务器外网IP
socketio.public.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
写socketio配置类
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
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);
}
}
下面写socket的接口以及实现
import com.szcl.verify.socketio.entity.PushMessage;
public interface ISocketIOService {
/**
* 推送的事件
*/
String PUSH_EVENT = "push_event";
/**
* 聊天的事件
*/
String IM_EVENT = "im_event";
/**
* 登录的事件
*/
String LOGIN_EVENT = "login_event";
/**
* 启动服务
*/
void start() throws Exception;
/**
* 停止服务
*/
void stop();
/**
* 推送信息
*/
void pushMessageToUser(PushMessage pushMessage);
}
import java.util.Iterator;
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.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(value = "socketIOService")
public class SocketIOServiceImpl implements ISocketIOService {
private Logger logger = LoggerFactory.getLogger(SocketIOServiceImpl.class);
/**
* 用来存已连接的客户端
*/
private static Map<String, SocketIOClient> clientMap = new ConcurrentHashMap<>();
@Autowired
private SocketIOServer server;
/**
* 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() {
// 监听客户端连接
server.addConnectListener(client -> {
String clientId = getParamsByClient(client);
if (clientId != null) {
clientMap.put(clientId, client);
logger.info("clientId: {} connected...", clientId);
}
});
// 监听客户端断开连接
server.addDisconnectListener(client -> {
String clientId = getParamsByClient(client);
if (clientId != null) {
clientMap.remove(clientId);
client.disconnect();
logger.info("clientId: {} disconnected...", clientId);
}
});
// 处理自定义的事件,与连接监听类似
server.addEventListener(PUSH_EVENT, PushMessage.class, (client, data, ackSender) -> {
logger.info("eventListener data: {}", data);
});
server.addEventListener(IM_EVENT, PushMessage.class, (client, data, ackSender) -> {
logger.info("eventListener data: {}", data);
});
server.start();
}
@Override
public void stop() {
/*Iterator<Map.Entry<String, SocketIOClient>> iterator = clientMap.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, SocketIOClient> node = iterator.next();
SocketIOClient cl = node.getValue();
cl.disconnect();
}*/
if (server != null) {
server.stop();
server = null;
logger.info("server stop!");
}
}
@Override
public void pushMessageToUser(PushMessage pushMessage) {
String clientIds = pushMessage.getClientId();
if (StringUtils.isNotBlank(clientIds)) {
for (String clientId : clientIds.split(",")) {
SocketIOClient client = clientMap.get(clientId);
if (client != null) {
client.sendEvent(pushMessage.getEvent(), pushMessage.getContent());
logger.info("push message: {}, toClientId: {}", pushMessage.getContent(), clientId);
}
}
}
}
/**
* 此方法为获取client连接中的参数,可根据需求更改
* @param client
* @return
*/
private String getParamsByClient(SocketIOClient client) {
// 从请求的连接中拿出参数(这里的clientId必须是唯一标识)
return client.getHandshakeData().getSingleUrlParam("clientId");
}
}
import io.swagger.annotations.ApiModelProperty;
public class PushMessage {
@ApiModelProperty(value = "登录用户编号")
private String clientId;
@ApiModelProperty(value = "推送事件")
private String event;
@ApiModelProperty(value = "推送内容")
private String content;
public PushMessage() {
}
public PushMessage(String clientId, String event, String content) {
this.clientId = clientId;
this.event = event;
this.content = content;
}
private PushMessage(Builder builder) {
setClientId(builder.clientId);
setEvent(builder.event);
setContent(builder.content);
}
public static Builder newBuilder() {
return new Builder();
}
public String getClientId() {
return clientId;
}
public void setClientId(String clientId) {
this.clientId = clientId;
}
public String getEvent() {
return event;
}
public void setEvent(String event) {
this.event = event;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public static final class Builder {
private String clientId;
private String event;
private String content;
private Builder() {
}
public Builder clientId(String val) {
clientId = val;
return this;
}
public Builder event(String val) {
event = val;
return this;
}
public Builder content(String val) {
content = val;
return this;
}
public PushMessage build() {
return new PushMessage(this);
}
}
}
在单一登录控制方法中推送消息通知客户端,账号已经在其他地方登录
/**
* 单一登录控制
* @param user
*/
private void checkSingleSingOn(User user) {
DefaultWebSecurityManager securityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
DefaultWebSessionManager sessionManager = (DefaultWebSessionManager) securityManager.getSessionManager();
//获取当前已登录的用户session列表
SessionDAO sessionDAO = sessionManager.getSessionDAO();
Collection<Session> sessions = sessionDAO.getActiveSessions();
for (Session session : sessions) {
//清除该用户以前登录时保存的session
Object obj = session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
SimplePrincipalCollection coll = (SimplePrincipalCollection) obj;
if(coll != null){
User userLogin = (User)coll.getPrimaryPrincipal();
if(user.getUsername().equals(userLogin.getUsername())){
socketIOService.pushMessageToUser(PushMessage.newBuilder()
.clientId(session.getId().toString())
.event(ISocketIOService.PUSH_EVENT)
.content("您的账号已在其他设备登陆,请重新登录或修改密码")
.build());
sessionDAO.delete(session);
}
}
}
}
页面消息推送实现
页面要引入socket.io.js,没有的可以从网上下载或者联系我,这里就不贴源码了。
<script type="text/javascript" th:src="@{/static/js/socket.io.js}"></script>
var socketUtil = (function () {
var socketUtil;
var _socket;
var _socketAddr;
var _clientId;
function constructor() {
return {
setSocketAddr: function (addr) {
_socketAddr = addr;
},
setClientId: function (clientId) {
_clientId = clientId;
}
};
}
return {
getInstance: function () {
if (socketUtil == null) {
socketUtil = constructor();
}
return socketUtil;
},
getConnection: function () {
var opts = {
query: 'clientId=' + _clientId
};
const socket = io.connect(_socketAddr, opts);
socket.on('connect', function () {
console.log("连接成功");
});
return socket;
}
}
})();
socketUtil.getInstance().setSocketAddr([[${session.socketAddr}]]);
socketUtil.getInstance().setClientId([[${session.sessionId}]]);
var socket = socketUtil.getConnection();
listener();
function listener() {
socket.on('push_event', function (data) {
layer.open({
type: 1
,title: false //不显示标题栏
,closeBtn: false
,area: '300px;'
,shade: 0.8
,id: 'LAY_layuipro' //设定一个id,防止重复弹出
,btn: ['确定']
,btnAlign: 'c'
,moveType: 1 //拖拽模式,0或者1
,content:
'<div style="padding: 50px; line-height: 22px; background-color: #393D49; color: #fff; font-weight: 300;">'+data+'</div>'
,success: function(layero){
var btn = layero.find('.layui-layer-btn');
btn.find('.layui-layer-btn0').attr({
href: '/index' ,target: ''
});
}
});
});
socket.on('disconnect', function () {
console.log('已下线!');
});
}
看下效果:
首先用admin用户登录
再用其他浏览器登录admin账户
效果如下:
聊天功能实现
先看效果:
看下聊天的效果:
前端代码:
<script type="text/javascript" th:src="@{/static/js/socket.io.js}"></script>
<script type="text/javascript" th:src="@{/static/lib/layui/lay/modules/layer.js}"></script>
<script type="text/javascript" th:src="@{/static/js/socketio-util.js}"></script>
layim相关:下载layim.zip
服务端获取好友接口:
@RequestMapping("/friend")
@ResponseBody
public String friend(){
BaseDTO<PageDTO<User>> dto = userService.list(1, 100, null);
List<User> allUsers = dto.getInfo().getList();
List<IMFriend> users = new ArrayList<>();
List<User> loginUsers = ShiroUtils.getLoginUsers();
loginUsers.forEach(user -> {
users.add(IMFriend.newBuilder()
.id(user.getSessionId())
.face("http://tp2.sinaimg.cn/1971109473/180/5686210542/0")
.name(user.getNickname()).build());
});
IMGroup onlineGroup = IMGroup.newBuilder()
.id(1)
.name("在线用户")
.nums(users.size())
.item(users)
.build();
/*IMGroup offlineGroup = IMGroup.newBuilder()
.id(1)
.name("我的好友")
.nums(0)
.item(null)
.build();*/
IMResponse response = IMResponse.newBuilder()
.status(1)
.msg("ok")
.data(Collections.singletonList(onlineGroup))
.build();
return GsonConvertUtil.toJson(response);
}
消息推送接口:
@GetMapping("/im/push")
@ApiOperation( "消息发送" )
@ResponseBody
public BaseDTO<String> pushMessage(@RequestParam String clientId,
@RequestParam String sourceClientId,
@RequestParam String content){
IMMessage message = IMMessage.newBuilder()
.clientId(clientId)
.sourceClientId(sourceClientId)
.content(content)
.build();
socketIOService.pushMessageToUser(PushMessage.newBuilder()
.clientId(clientId)
.event(ISocketIOService.IM_EVENT)
.content(GsonConvertUtil.toJson(message)).build());
return DtoConvertUtil.toDTO(null, "成功", Constants.CODE_SUCCESS, true);
}