基于Netty和WebSocket实现的简易版聊天网页
1、pom.xml引入依赖
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.43.Final</version>
</dependency>
2、建立netty服务器启动类
package com.demo.netty.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NettyServer {
private static final Logger logger = LoggerFactory.getLogger(NettyServer.class);
public static void main(String[] args) {
logger.info("正在启动websocket服务器");
//创建两个线程池,用于Acceptor的主"线程池"以及用于I/O工作的从"线程池"
NioEventLoopGroup bossGroup = new NioEventLoopGroup();
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
//创建Netty服务器启动对象
ServerBootstrap serverBootstrap = new ServerBootstrap();
//初始化服务器启动对象
serverBootstrap
//指定使用上面创建的两个线程池
.group(bossGroup, workerGroup)
//指定channel通道类型
.channel(NioServerSocketChannel.class)
//指定通道初始化器用来加载当Channel收到时间消息后,
.childHandler(new WebSocketChannelInitializer());
//绑定服务器端口,以同步的方式启动服务器
ChannelFuture future = serverBootstrap.bind(18090).sync();
if (future.isSuccess()) {
logger.info("webSocket服务器启动成功:" + future);
}
//等待服务器关闭
future.channel().closeFuture().sync();
} catch (InterruptedException e) {
logger.error("webSocket服务器启动出错!", e);
} finally {
//关闭服务器
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
logger.info("websocket服务器已关闭");
}
}
}
3、创建初始化类
package com.demo.netty.server;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
public class WebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {
/**
* 初始化通道
* 在这个方法中去加载对应的ChannelHandler
*
* @param socketChannel
* @throws Exception
*/
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
//获取通道,将一个一个的ChannelHandler添加到管道中
ChannelPipeline pipeline = socketChannel.pipeline();
//添加一个HTTP的编解码器
pipeline.addLast(new HttpServerCodec());
//添加一个用于支持大数据流的支持
pipeline.addLast(new ChunkedWriteHandler());
//添加一个聚合器,这个聚合器主要是讲HttpMessage聚合成FullHttpRequest/Response
pipeline.addLast(new HttpObjectAggregator(1024 * 64));
//需要指定接收请求的路由
//必须使用以ws后缀的URL才能访问
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
//添加自定义的Handler
pipeline.addLast(new ChatHandler());
}
}
4、创建助手类
package com.demo.netty.server;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
//用来保存所有的客户端连接
private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
private static SimpleDateFormat sdf = new SimpleDateFormat();
//当Channel中有新的时间消息会自动调用
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
//当接收到数据后自动调用
//获取客户端发送过来的文本消息
String text = textWebSocketFrame.text();
System.out.println("接收到消息数据为:" + text);
//将消息发送到所有的客户端
for (Channel client : clients) {
client.writeAndFlush(new TextWebSocketFrame(sdf.format(new Date()) + ":" + text));
}
}
//当有新的客户端连接服务器之后,会自动调用这个方法
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//将新的通道加入到clients
clients.add(ctx.channel());
}
}
5、前端页面
chat.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>在线聊天室</title>
</head>
<body>
<input type="text" id="message">
<input type="button" value="发送消息" onclick="javascript:sendMsg();"><br/>
接收到的消息:
<p id="server_message" style="background-color: #AAAAAA"></p>
<script>
var websocket = null;
//判断当前浏览器是否支持websocket
if (window.WebSocket) {
websocket = new WebSocket("ws://127.0.0.1:18090/ws");
websocket.onopen = function () {
console.log("建立连接");
}
websocket.onclose = function () {
console.log("断开连接");
}
websocket.onmessage = function (e) {
console.log("接收到服务器消息:" + e.data);
var server_message = document.getElementById("server_message")
server_message.innerHTML += e.data + "<br/>";
}
} else {
alert("当前浏览器不支持websocket");
}
//发送消息到服务端
function sendMsg() {
var message = document.getElementById("message")
websocket.send(message.value);
console.log("发送消息到服务器:" + message.value);
message.value = "";//清空输入框
}
</script>
</body>
</html>
6、测试效果
启动NettyServer类,然后打开2个浏览器窗口访问chat.html网页,分别输入消息并且发送