服务器端
public class MyServer {
public static void main(String[] args) throws Exception {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO)) //在bossGroup增加一个日志处理器
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//基于http协议、使用http的编码和解码器
pipeline.addLast(new HttpServerCodec());
//以块方式写、添加ChunkedWriteHandler处理器
pipeline.addLast(new ChunkedWriteHandler());
/**
* 因为http协议传输过程中是分段的、HttpObjectAggregator可以将多个段进行聚合
* 所以浏览器发送大量数据时、会发出多次http请求
*/
pipeline.addLast(new HttpObjectAggregator(8192));
/**
* 对应WebSocket ,他的数据以帧方式传递
* WebSocketServer下面有六个子类
* 浏览器请求时 ws://localhost:9999/hello 表示请求的uri
* WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议,保持长连接
*/
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
//自定义handler,处理业务逻辑
pipeline.addLast(new MyTextWebSocketFrameHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
自定义Handler
public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println("服务器端收到消息 " + msg.text());
//回复浏览器消息
ctx.channel().writeAndFlush(new TextWebSocketFrame("服务器时间 " + LocalDateTime.now() + " " + msg.text()));
}
//当web客户端连接后、触发方法
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//id表示唯一的标识,LongText是唯一的 ShortText不是唯一的
System.out.println("handlerAdded被调用了"+ctx.channel().id().asLongText());
System.out.println("handlerAdded被调用了"+ctx.channel().id().asShortText());
super.handlerAdded(ctx);
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerRemoved被调用了"+ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("异常发生" + cause.getMessage());
ctx.close(); //关闭连接
}
}
前端页面代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var socket;
//判断当前浏览器是否支持WebSocket
if (window.WebSocket) {
//go on
socket = new WebSocket("ws://localhost:9999/hello");
//相当于channelRead ev 收到服务器端回送的消息
socket.onmessage = function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + ev.data;
}
//相当于连接开始
socket.onopen = function (ev) {
var rt = document.getElementById("responseText");
rt.value = "连接开启...";
}
//相当于连接关闭(感知连接关闭)
socket.onclose = function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + "链接关闭了...";
}
} else {
alert("当前浏览器不支持WebSocket编程")
}
//发送消息服务器
function send(message) {
if (!window.socket) { //判断socket是否建立好
return;
}
if (socket.readyState == WebSocket.OPEN) {
//通过socket发送消息
socket.send(message);
} else {
alert("链接没有开启");
}
}
</script>
<form onsubmit="return false">
<textarea name="message" style="height: 300px;width: 300px"></textarea>
<input type="button" value="发送消息" onclick="send(this.form.message.value)">
<textarea id="responseText" style="height: 300px;width: 300px"></textarea>
<input type="button" value="清空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>