不说废话,直接上干货,代码只贴关键代码。
后端使用netty-socketio
<dependency>
<groupId>com.corundumstudio.socketio</groupId>
<artifactId>netty-socketio</artifactId>
<version>2.0.6</version>
</dependency>
socketio启动类
@Component
@Slf4j
public class SocketIORunner implements CommandLineRunner {
@Autowired
private SocketIOServer socketIOServer;
@Override
public void run(String... args) throws Exception {
socketIOServer.start();
log.info("socket.io启动成功!");
}
}
socketio配置类
@Configuration
@Slf4j
public class SocketIOConfig {
@Bean
public SocketIOServer socketIOServer() {
com.corundumstudio.socketio.Configuration configuration = new com.corundumstudio.socketio.Configuration();
configuration.setPort(9092);
SocketIOServer server = new SocketIOServer(configuration);
server.addConnectListener(client -> {
log.info("客户端:{}已连接:", client.getSessionId());
});
server.addDisconnectListener(client -> {
log.info("客户端:{}已断开连接:", client.getSessionId());
});
server.addEventListener("msgEvent", String.class, (client, s, ackRequest) -> {
log.info("客户端: {}发送消息-{}", client.getSessionId(), s);
server.getBroadcastOperations().sendEvent("msgEvent", s);
});
return server;
}
}
前端 使用html+js
<!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="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.7.2/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="disconnect" onClick='disconnect()'>Disconnect</button>
<button id="send" onClick='send()'/>Send Message</button>
</body>
<script type="text/javascript">
/**
* 前端js的 socket.emit("事件名","参数数据")方法,是触发后端自定义消息事件的时候使用的,
* 前端js的 socket.on("事件名",匿名函数(服务器向客户端发送的数据))为监听服务器端的事件
**/
const socket = io("http://localhost:9092");
// client-side
socket.on("connect", () => {
status_update("Connected to Server");
});
socket.on("disconnect", () => {
status_update("Disconnected from Server");
});
socket.on("msgEvent", (arg) => {
status_update(arg);
});
//断开连接
function disconnect() {
socket.disconnect();
}
function status_update(txt){
document.getElementById('status').innerHTML = txt;
}
//点击发送消息触发
function send() {
var msg = "我很好的,是的.";
socket.emit('msgEvent', msg);
};
</script>
</html>
成功连接如图
说明,目前客户端连接时,会触发两次,应该是框架bug,使用中有问题可参考这netty-socketio