请写一个netty websocket
时间: 2024-03-03 18:48:30 浏览: 94
好的,以下是一个使用 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());
}
}
}
```
这个示例代码启动一个 WebSocket 服务器,并监听本地的 8080 端口。当有新的 WebSocket 连接建立时,服务器会将连接加入到一个列表中,当有消息发送到服务器时,服务器会将消息转发给所有连接。
阅读全文