netty-socketio概述
netty-socketio 概述
netty-socketio是⼀个开源的Socket.io服务器端的⼀个java的实现,它基于Netty框架,可⽤于服务端推送消息给客户端。
websocket和socket说到服务端推送技术,⼀般会涉及WebSocket,WebSocket是HTML5最新提出的规范,虽然主流浏览器都已经⽀持,但仍然可能有不兼容的情况,为了兼容所有浏览器,给程序员提供⼀致的编程体验,SocketIO将WebSocket、AJAX和其它的通信⽅式全部封装成了统⼀的通信接⼝,也就是说,使⽤SocketIO时不⽤担⼼兼容问题,底层会⾃动选⽤最佳的通信⽅式。
netty-socketio 框架事件流程
netty-socketio ⽰例demo
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId&undumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>1.7.17</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.4</version>
<scope>provided</scope>
</dependency>
</dependencies>
启动类 NettySocketioApplication
@SpringBootApplication
@Slf4j
public class NettySocketioApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(NettySocketioApplication.class, args);
}
@Autowired
private SocketIOServer socketIOServer;
@Override
public void strings) {
socketIOServer.start();
}
}
Message
@Data
public class Message {
private String msg;
}
配置类 NettySocketioConfig
@Configuration
public class NettySocketioConfig {
/**
* netty-socketio服务器
*/
@Bean
public SocketIOServer socketIOServer() {
config.setPort(9092);
SocketIOServer server = new SocketIOServer(config);
return server;
}
/**
* ⽤于扫描netty-socketio的注解,⽐如 @OnConnect、@OnEvent
*/
@Bean
public SpringAnnotationScanner springAnnotationScanner() {
return new SpringAnnotationScanner(socketIOServer());
}
}
消息处理器 MessageEventHandler
@Component
@Slf4j
public class MessageEventHandler {
@Autowired
private SocketIOServer socketIoServer;
public static ConcurrentMap<String, SocketIOClient> socketIOClientMap = new ConcurrentHashMap<>(); /**
* 客户端连接的时候触发
*
* @param client
*/
@OnConnect
public void onConnect(SocketIOClient client) {
String mac = HandshakeData().getSingleUrlParam("mac");
//存储SocketIOClient,⽤于发送消息
socketIOClientMap.put(mac, client);
//回发消息
client.sendEvent("message", "onConnect back");
log.info("客户端:" + SessionId() + "已连接,mac=" + mac);
}
/
**
* 客户端关闭连接时触发
*
* @param client
*/
@OnDisconnect
public void onDisconnect(SocketIOClient client) {
log.info("客户端:" + SessionId() + "断开连接");
}
/**
* 客户端事件
*
* @param client 客户端信息
* @param request 请求信息
* @param data 客户端发送数据
*/
@OnEvent(value = "messageevent")
public void onEvent(SocketIOClient client, AckRequest request, Message data) {
//回发消息
client.sendEvent("messageevent", "我是服务器都安发送的信息");
//⼴播消息
sendBroadcast();
}
/**
* ⼴播消息
*/
public void sendBroadcast() {
for (SocketIOClient client : socketIOClientMap.values()) {
if (client.isChannelOpen()) {
client.sendEvent("Broadcast", "当前时间", System.currentTimeMillis());
}
}
}
}
html 页⾯
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1, maximum-scale=1, user-scalable=no"> <title>websocket-java-socketio</title>
<script src="cdn.bootcss/socket.io/2.2.0/socket.io.js"></script>
</head>
<body>
<h1>Socket.io Test</h1>
<div><p id="status">Waiting for input</p></div>
<div><p id="message">hello world!</p></div>
<button id="connect" onClick='connect()'/>Connect</button>
<button id="disconnect" onClick='disconnect()'>Disconnect</button>
<button id="send" onClick='send()'/>Send Message</button>
</body>
<script type="text/javascript">
/**
* 前端js的 it("事件名","参数数据")⽅法,是触发后端⾃定义消息事件的时候使⽤的,
* 前端js的 ("事件名",匿名函数(服务器向客户端发送的数据))为监听服务器端的事件
**/
var socket = io.connect("localhost:9092?mac=2");
var firstconnect = true;
function connect() {
if(firstconnect) {
//('reconnect', function(){ status_update("Reconnected to Server"); });
//('reconnecting', function( nextRetry ){ status_update("Reconnecting in "
//+ nextRetry + " seconds"); });
//('reconnect_failed', function(){ message("Reconnect Failed"); });
//firstconnect = false;
} else {
ect();
}
}
//监听服务器连接事件
<('connect', function(){ status_update("Connected to Server"); });
//监听服务器关闭服务事件
<('disconnect', function(){ status_update("Disconnected from Server"); });
//监听服务器端发送消息事件
<('messageevent', function(data) {
message(data)
//console.log("服务器发送的消息是:"+data);
});
/
/断开连接
function disconnect() {
socket.disconnect();
}
function message(data) {
}
function status_update(txt){
}
function esc(msg){
place(/</g, '<').replace(/>/g, '>');
}
//点击发送消息触发
function send() {
console.log("点击了发送消息,开始向服务器发送消息") var msg = "我很好的,是的.";
};
</script>
</html>
执⾏输出
运⾏ SpringBoot 服务器
> mvn spring-boot:run
点击⽹页按钮
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论