用java写一个netty websocket服务端和客户端代码实现互相通讯
时间: 2023-08-04 10:28:58 浏览: 160
以下是一个使用 Netty 实现 WebSocket 服务端和客户端的示例代码:
服务端代码:
```java
public class WebSocketServer {
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(group)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new WebSocketServerProtocolHandler("/chat"));
pipeline.addLast(new TextWebSocketFrameHandler());
}
});
ChannelFuture future = bootstrap.bind(8080).sync();
future.channel().closeFuture().sync();
} finally {
group.shutdownGracefully();
}
}
private static class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
private final List<Channel> channels = new ArrayList<>();
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
String text = msg.text();
System.out.println("Received message: " + text);
for (Channel channel : channels) {
channel.writeAndFlush(new TextWebSocketFrame("Server: " + text));
}
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
channels.add(ctx.channel());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
channels.remove(ctx.channel());
}
}
}
```
客户端代码:
```java
public class WebSocketClient {
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
WebSocketClientHandler handler = new WebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(
new URI("ws://localhost:8080/chat"), WebSocketVersion.V13, null, false, new DefaultHttpHeaders()));
Bootstrap bootstrap = new Bootstrap()
.group(group)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpClientCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new WebSocketClientProtocolHandler(handler.handshaker()));
pipeline.addLast(handler);
}
});
Channel channel = bootstrap.connect("localhost", 8080).sync().channel();
handler.handshakeFuture().sync();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
while (true) {
String line = reader.readLine();
if (line == null) {
break;
}
channel.writeAndFlush(new TextWebSocketFrame(line));
}
} finally {
group.shutdownGracefully();
}
}
private static class WebSocketClientHandler extends SimpleChannelInboundHandler<Object> {
private final WebSocketClientHandshaker handshaker;
private ChannelPromise handshakeFuture;
public WebSocketClientHandler(WebSocketClientHandshaker handshaker) {
this.handshaker = handshaker;
}
public ChannelFuture handshakeFuture() {
return handshakeFuture;
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
handshakeFuture = ctx.newPromise();
}
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
handshaker.handshake(ctx.channel());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("WebSocket Client disconnected!");
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
if (!handshaker.isHandshakeComplete()) {
handshaker.finishHandshake(ctx.channel(), (FullHttpResponse) msg);
System.out.println("WebSocket Client connected!");
handshakeFuture.setSuccess();
return;
}
if (msg instanceof FullHttpResponse) {
FullHttpResponse response = (FullHttpResponse) msg;
throw new IllegalStateException("Unexpected FullHttpResponse (getStatus=" + response.status() +
", content=" + response.content().toString(CharsetUtil.UTF_8) + ')');
}
TextWebSocketFrame frame = (TextWebSocketFrame) msg;
System.out.println("Received message: " + frame.text());
}
}
}
```
这个示例代码启动了一个 WebSocket 服务器,监听本地的 8080 端口。当有新的 WebSocket 连接建立时,服务器会将连接加入到一个列表中,当有消息发送到服务器时,服务器会将消息转发给所有连接。同时,客户端与服务器建立连接,发送消息并接收服务器返回的消息。
阅读全文