Front-end code: (I use vue here)
let socket = new WebSocket('ws://localhost:8888/chat');
// 连接成功时触发的事件
socket.onopen = () => {
console.log('连接成功');
// 发送消息给服务器
socket.send(JSON.stringify({
//传送的数据,记住一定要写在连接之后
}));
};
// 接收到消息时触发的事件
socket.onmessage = (event) => {
console.log('接收到消息:', event.data);
};
// 断开连接时触发的事件
socket.onclose = () => {
console.log('连接已断开');
};
rear end:
//创建两个线程组 boosGroup、workerGroup
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try{
//创建服务端的启动对象,设置参数
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
pipeline.addLast(new HttpServerCodec())
.addLast(new ChunkedWriteHandler())
.addLast(new HttpObjectAggregator(1024*64))
.addLast(new WebSocketServerProtocolHandler("/chat"))
.addLast(new ServerHandler());
}
});
ChannelFuture future = bootstrap.bind(8888).sync();
System.out.println("netty start!");
//对关闭通道进行监听
future.channel().closeFuture().sync();
}
finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}