netty websocket 示例代码
时间: 2023-08-30 08:11:08 浏览: 164
以下是一个简单的 Netty WebSocket 示例代码:
```java
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
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.WebSocketFrameAggregator;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.concurrent.DefaultThreadFactory;
public class WebSocketServer {
private static final int PORT = 8080;
public static void main(String[] args) throws Exception {
EventLoopGroup bossGroup = new NioEventLoopGroup(1, new DefaultThreadFactory("boss"));
EventLoopGroup workerGroup = new NioEventLoopGroup(0, new DefaultThreadFactory("worker"));
try {
ServerBootstrap bootstrap = new ServerBootstrap()
.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new HttpObjectAggregator(65536));
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new WebSocketFrameAggregator(65536));
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
pipeline.addLast(new WebSocketServerHandler());
}
});
Channel ch = bootstrap.bind(PORT).sync().channel();
System.out.println("WebSocket server started at port " + PORT + ".");
System.out.println("Open your browser and navigate to http://localhost:" + PORT + "/");
ch.closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
```
上述代码创建了一个 Netty WebSocket 服务器,监听端口为 8080。新连接会通过 `ChannelInitializer` 进行处理,其中添加了以下几个处理器:
- `HttpServerCodec`:用于将 HTTP 请求和响应编解码为 Netty 的 `HttpRequest` 和 `HttpResponse` 对象。
- `HttpObjectAggregator`:用于将 HTTP 消息的多个部分合并成一个完整的消息。
- `ChunkedWriteHandler`:用于处理大文件或者大数据流,将数据以块(Chunk)的形式写入到客户端。
- `WebSocketFrameAggregator`:用于将 WebSocket 帧的多个部分合并成一个完整的帧。
- `WebSocketServerProtocolHandler`:用于处理 WebSocket 握手和帧的编解码。
- `WebSocketServerHandler`:自定义的处理器,用于处理客户端的 WebSocket 帧。
`WebSocketServerHandler` 的示例代码如下:
```java
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrameAggregator;
public class WebSocketServerHandler extends SimpleChannelInboundHandler<WebSocketFrame> {
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client connected: " + ctx.channel().remoteAddress());
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("Client disconnected: " + ctx.channel().remoteAddress());
}
@Override
protected void channelRead0(ChannelHandlerContext ctx, WebSocketFrame frame) throws Exception {
if (frame instanceof TextWebSocketFrame) {
String text = ((TextWebSocketFrame) frame).text();
System.out.println("Received message: " + text);
ctx.channel().writeAndFlush(new TextWebSocketFrame("Server received: " + text));
} else {
throw new UnsupportedOperationException("Unsupported frame type: " + frame.getClass().getName());
}
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.err.println("Exception caught: " + cause.getMessage());
ctx.close();
}
}
```
上述代码实现了 `SimpleChannelInboundHandler` 接口,用于处理客户端发送的 WebSocket 帧。当收到 `TextWebSocketFrame` 类型的帧时,会将其内容打印到控制台,并将其转发给客户端。其他类型的帧会抛出异常。
客户端可以通过 JavaScript 代码连接到服务器:
```javascript
let socket = new WebSocket("ws://localhost:8080/ws");
socket.onopen = function() {
console.log("Connected to WebSocket server.");
socket.send("Hello, WebSocket server!");
};
socket.onmessage = function(event) {
console.log("Received message: " + event.data);
};
socket.onclose = function(event) {
console.log("Disconnected from WebSocket server.");
};
```
阅读全文