java netty 實現 websocket 服務端和客戶端雙向通訊 實現心跳和斷線重連 完整示例
maven依賴
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.97.Final</version>
</dependency>
服務端
服務端心跳事件處理 ServerHeartbeatHandler
package com.sux.demo.websocket2;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
public class ServerHeartbeatHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) { // 讀空閒
System.out.println("斷開與客戶端的連線, channel id=" + ctx.channel().id());
ctx.channel().close();
} else if (event.state() == IdleState.WRITER_IDLE) { // 寫空閒
} else if (event.state() == IdleState.ALL_IDLE) { // 讀寫空閒
}
}
}
}
定時傳送心跳的類 HeartbeatThread
package com.sux.demo.websocket2;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.PingWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
public class HeartbeatThread extends Thread {
private ChannelGroup channelGroup;
private boolean running = true;
public HeartbeatThread(Channel channel) {
channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
channelGroup.add(channel);
}
public HeartbeatThread(ChannelGroup channelGroup) {
this.channelGroup = channelGroup;
}
@Override
public void run() {
while (running) {
try {
if (channelGroup.size() > 0) {
System.out.println("傳送心跳");
for (Channel channel : channelGroup) {
channel.writeAndFlush(new PingWebSocketFrame());
}
}
Thread.sleep(2000);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public void close() {
running = false;
}
}
服務端封裝 WebSocketServer
package com.sux.demo.websocket2;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import java.util.concurrent.TimeUnit;
public class WebSocketServer {
private EventLoopGroup bossGroup;
private EventLoopGroup workerGroup;
private WebSocketServerHandler webSocketServerHandler;
public WebSocketServer() {
//建立兩個執行緒組 boosGroup、workerGroup
bossGroup = new NioEventLoopGroup();
workerGroup = new NioEventLoopGroup();
webSocketServerHandler = new WebSocketServerHandler();
}
public void start(int port, String name) {
try {
//建立服務端的啟動物件,設定引數
ServerBootstrap bootstrap = new ServerBootstrap();
//設定兩個執行緒組boosGroup和workerGroup
bootstrap.group(bossGroup, workerGroup)
//設定服務端通道實現型別
.channel(NioServerSocketChannel.class)
//設定執行緒佇列得到連線個數
.option(ChannelOption.SO_BACKLOG, 128)
//設定保持活動連線狀態
.childOption(ChannelOption.SO_KEEPALIVE, true)
//使用匿名內部類的形式初始化通道物件
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//給pipeline管道設定處理器
socketChannel.pipeline().addLast(new HttpServerCodec());
socketChannel.pipeline().addLast(new HttpObjectAggregator(65536));
socketChannel.pipeline().addLast(new WebSocketServerProtocolHandler("/websocket", null, false, 65536, false, false, false, 10000));
socketChannel.pipeline().addLast(new IdleStateHandler(5, 2, 0, TimeUnit.SECONDS));
socketChannel.pipeline().addLast(new ServerHeartbeatHandler());
socketChannel.pipeline().addLast(webSocketServerHandler);
}
});//給workerGroup的EventLoop對應的管道設定處理器
//繫結埠號,啟動服務端
ChannelFuture channelFuture = bootstrap.bind(port).sync();
System.out.println(name + " 已啟動");
// 定時傳送心跳
startHeartbeat();
//對通道關閉進行監聽
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
public void startHeartbeat() {
HeartbeatThread thread = new HeartbeatThread(webSocketServerHandler.getChannelGroup());
thread.start();
}
public void send(String text) {
for (Channel channel : webSocketServerHandler.getChannelGroup()) {
channel.writeAndFlush(new TextWebSocketFrame(Unpooled.copiedBuffer(text, CharsetUtil.UTF_8)));
}
}
public boolean hasClient() {
return webSocketServerHandler.getChannelGroup().size() > 0;
}
}
說明:new IdleStateHandler(5, 2, 0, TimeUnit.SECONDS)第一個引數5表示讀空閒時間間隔是5秒,第二個引數2表示寫空閒的時間間隔是2秒,第3個引數0表示不檢測讀寫空閒。在ServerHeartbeatHandler程式碼中,讀寫空閒時斷開與客戶端的連線。
服務端訊息處理 WebSocketServerHandler
package com.sux.demo.websocket2;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.*;
import io.netty.util.concurrent.GlobalEventExecutor;
@ChannelHandler.Sharable
public class WebSocketServerHandler extends SimpleChannelInboundHandler<Object> {
private ChannelGroup channelGroup;
public WebSocketServerHandler() {
channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
}
public ChannelGroup getChannelGroup() {
return channelGroup;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
if (msg instanceof PongWebSocketFrame) {
System.out.println("收到客戶端" + ctx.channel().remoteAddress() + "發來的心跳:PONG");
}
if (msg instanceof TextWebSocketFrame) {
TextWebSocketFrame frame = (TextWebSocketFrame) msg;
System.out.println("收到客戶端" + ctx.channel().remoteAddress() + "發來的訊息:" + frame.text());
/* // 測試轉發訊息
for (Channel channel : channelGroup) {
if (!ctx.channel().id().toString().equals(channel.id().toString())) {
channel.writeAndFlush(new TextWebSocketFrame(Unpooled.copiedBuffer(frame.text(), CharsetUtil.UTF_8)));
System.out.println("服務端向客戶端 " + channel.id().toString() + " 轉發訊息:" + frame.text());
}
} */
}
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
channelGroup.add(ctx.channel());
System.out.println("客戶端" + ctx.channel().id().toString() + "已連線");
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
channelGroup.remove(ctx.channel());
System.out.println("客戶端" + ctx.channel().id() + "已斷開");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}
服務端測試主機 WebSocketServerHost
package com.sux.demo.websocket2;
public class WebSocketServerHost {
public static void main(String[] args) {
WebSocketServer webSocketServer = new WebSocketServer();
SendDataToClientThread thread = new SendDataToClientThread(webSocketServer);
thread.start();
webSocketServer.start(40005, "WebSocket服務端");
}
}
class SendDataToClientThread extends Thread {
private WebSocketServer webSocketServer;
private int index = 1;
public SendDataToClientThread(WebSocketServer webSocketServer) {
this.webSocketServer = webSocketServer;
}
@Override
public void run() {
try {
while (index <= 5) {
if (webSocketServer.hasClient()) {
String msg = "服務端傳送的測試訊息, index = " + index;
webSocketServer.send(msg);
index++;
}
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
客戶端
客戶端心跳事件處理 ClientHeartbeatHandler
package com.sux.demo.websocket2;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
public class ClientHeartbeatHandler extends ChannelInboundHandlerAdapter {
@Override
public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
if (evt instanceof IdleStateEvent) {
IdleStateEvent event = (IdleStateEvent) evt;
if (event.state() == IdleState.READER_IDLE) { // 讀空閒
System.out.println("斷開與服務端的連線");
ctx.channel().close();
} else if (event.state() == IdleState.WRITER_IDLE) { // 寫空閒
} else if (event.state() == IdleState.ALL_IDLE) { // 讀寫空閒
}
}
}
}
客戶端封裝 WebSocketClient
package com.sux.demo.websocket2;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.DefaultHttpHeaders;
import io.netty.handler.codec.http.HttpClientCodec;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshaker;
import io.netty.handler.codec.http.websocketx.WebSocketClientHandshakerFactory;
import io.netty.handler.codec.http.websocketx.WebSocketClientProtocolHandler;
import io.netty.handler.codec.http.websocketx.WebSocketVersion;
import io.netty.handler.timeout.IdleStateHandler;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.concurrent.TimeUnit;
public class WebSocketClient {
private NioEventLoopGroup eventExecutors;
private Channel channel;
private HeartbeatThread heartbeatThread;
public WebSocketClient() {
eventExecutors = new NioEventLoopGroup();
}
public Channel getChannel() {
return channel;
}
public void connect(String ip, int port, String name) {
try {
WebSocketClientHandshaker handshaker = WebSocketClientHandshakerFactory.newHandshaker(
new URI("ws://" + ip + ":" + port + "/websocket"), WebSocketVersion.V13, null, false, new DefaultHttpHeaders());
WebSocketClientHandler handler = new WebSocketClientHandler(handshaker);
ClientHeartbeatHandler heartbeatHandler = new ClientHeartbeatHandler();
//建立bootstrap物件,配置引數
Bootstrap bootstrap = new Bootstrap();
//設定執行緒組
bootstrap.group(eventExecutors)
//設定客戶端的通道實現型別
.channel(NioSocketChannel.class)
//使用匿名內部類初始化通道
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//新增客戶端通道的處理器
ch.pipeline().addLast(new HttpClientCodec());
ch.pipeline().addLast(new HttpObjectAggregator(65536));
ch.pipeline().addLast(new WebSocketClientProtocolHandler(handshaker, true, false));
ch.pipeline().addLast(new IdleStateHandler(5, 2, 0, TimeUnit.SECONDS));
ch.pipeline().addLast(heartbeatHandler);
ch.pipeline().addLast(handler);
}
});
// 連線服務端
ChannelFuture channelFuture = bootstrap.connect(ip, port);
// 在連線關閉後嘗試重連
channelFuture.channel().closeFuture().addListener(future -> {
try {
if (heartbeatThread != null && heartbeatThread.isAlive()) {
System.out.println("停止傳送心跳執行緒");
heartbeatThread.close();
}
Thread.sleep(2000);
System.out.println("重新連線服務端");
connect(ip, port, name); // 重新連線服務端
} catch (Exception e) {
e.printStackTrace();
}
});
channelFuture.sync();
channel = channelFuture.channel();
System.out.println(name + " 已啟動");
// 定時傳送心跳
heartbeatThread = new HeartbeatThread(channel);
heartbeatThread.start();
//對通道關閉進行監聽
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException | URISyntaxException e) {
e.printStackTrace();
} finally {
}
}
}
說明:new IdleStateHandler(5, 2, 0, TimeUnit.SECONDS)第一個引數5表示讀空閒時間間隔是5秒,第二個引數2表示寫空閒的時間間隔是2秒,第3個引數0表示不檢測讀寫空閒。在ClientHeartbeatHandler程式碼中,讀寫空閒時斷開與服務端的連線。
客戶端訊息處理 WebSocketClientHandler
package com.sux.demo.websocket2;
import io.netty.channel.*;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.websocketx.*;
@ChannelHandler.Sharable
public class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {
private WebSocketClientHandshaker handshaker;
private ChannelPromise handshakeFuture;
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
this.handshaker = handshaker;
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) {
if (!handshaker.isHandshakeComplete()) {
try {
handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
handshakeFuture.setSuccess();
} catch (WebSocketHandshakeException e) {
handshakeFuture.setFailure(e);
}
return;
}
if (msg instanceof PongWebSocketFrame) {
System.out.println("收到服務端" + ctx.channel().remoteAddress() + "發來的心跳:PONG");
}
if (msg instanceof TextWebSocketFrame) {
TextWebSocketFrame frame = (TextWebSocketFrame) msg;
System.out.println("收到服務端" + ctx.channel().remoteAddress() + "發來的訊息:" + frame.text()); // 接收服務端傳送過來的訊息
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) {
handshakeFuture = ctx.newPromise();
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
}
@Override
public void channelInactive(ChannelHandlerContext ctx) {
System.out.println("客戶端下線");
}
@Override
public void channelReadComplete(ChannelHandlerContext ctx) {
ctx.flush();
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
ctx.close();
}
}
客戶端測試主機 WebSocketClientHost
package com.sux.demo.websocket2;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.CharsetUtil;
public class WebSocketClientHost {
public static void main(String[] args) {
WebSocketClient webSocketClient = new WebSocketClient();
SendDataToServerThread thread = new SendDataToServerThread(webSocketClient);
thread.start();
webSocketClient.connect("127.0.0.1", 40005, "WebSocket客戶端");
}
}
class SendDataToServerThread extends Thread {
private WebSocketClient webSocketClient;
private int index = 1;
public SendDataToServerThread(WebSocketClient webSocketClient) {
this.webSocketClient = webSocketClient;
}
@Override
public void run() {
try {
while (index <= 5) {
Channel channel = webSocketClient.getChannel();
if (channel != null && channel.isActive()) {
String msg = "客戶端傳送的測試訊息, index = " + index;
channel.writeAndFlush(new TextWebSocketFrame(Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8)));
index++;
}
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
測試
測試一
步驟:先啟動服務端,再啟動客戶端
現象:客戶端與服務端互發訊息,訊息發完後,互發心跳
測試二
步驟:先啟動服務端,再啟動客戶端,然後關閉服務端,過一會再啟動服務端
現象:客戶端斷線重連,通訊恢復,正常發訊息和心跳
測試三
步驟:先啟動客戶端,過一會再啟動服務端
現象:服務端啟動後,客戶端連上服務端,正常通訊,互發訊息,訊息發完互發心跳
遇到的問題
1. 心跳問題
如果客戶端想確認服務端是否線上,就向服務端發PING,如果服務端線上,服務端就會回一個PONG,客戶端就能收到PONG,如果客戶端長時間收不到服務端的訊息,就會觸發讀空閒,然後斷開與服務端的連線,觸發斷線重連。
如果服務端想確認客戶端是否線上,就向客戶端發PING,如果客戶端線上,客戶端就會回一個PONG,服務端就能收到PONG,如果服務端長時間收不到客戶端的訊息,就會觸發讀空閒,然後斷開與客戶端的連線。
WebSocketClientProtocolHandler和WebSocketServerProtocolHandler類都有一個dropPongFrames引數,預設為true,如果你在讀空閒時寫了斷開連線的操作,要把dropPongFrames設定為false,這樣才可以在訊息處理handler中接收到PONG,否則即使對方回應了PONG,也會被丟棄掉,導致觸發讀空閒,導致連線被斷開。
2. 如何發心跳
我在網上看到兩種方式
方式一:
channel.writeAndFlush(new PingWebSocketFrame());
方式二:
channel.writeAndFlush(new TextWebSocketFrame("PING"));
方式一,對方收到心跳,會自動回一個PONG,需要把dropPongFrames設定為false才能收到對方回應的PONG。
方式二,對方收到心跳,需要手動回一個PONG,用TextWebSocketFrame包裝,我方可以像收普通訊息那樣收到這個文字PONG。
3. 在寫空閒時發心跳需要注意
如果我方一直向對方發業務資料,就不會觸發寫空閒,就不會發心跳,就收不到對方的回應PONG,如果對方又沒有向我方發業務資料,就會觸發我方的讀空閒,如果在我方讀空閒中寫了斷開邏輯,連線就會被主動斷開,這種情況是錯誤的。所以本文的程式碼中,是在一個執行緒中一直定時傳送PING,這樣如果對方線上,也會一直定時回應PONG,只要對方線上就不會觸發我方的讀空閒,如果對方不線上,才會觸發我方的讀空閒。