要实现网页版的聊天室,用http协议是不行的,因为http协议是个短链接,发过去之后拿到响应就死掉了。
http1.1出现了keepAlive。这里可以实现长连接。
所谓长连接,就是可以重用之前建立的tcp连接。
但是,keepAlive是一个假的长连接。server可以随时断掉,server和client是不对等的状态。另外,它的实现是client要不断向server询问是否有新数据,每次询问的时候,都要携带header(http协议规范),这些不必要的数据,增加了网络带宽的压力。
于是,出现了能够真正实现长连接的websocket协议。
在该协议下,tcp连接建立之后,client和server的交互不再需要携带header。并且,client和server是对等的,它们都可以向对方发送信息。
server:
public class WebSocketServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup,workerGroup).channel(NioServerSocketChannel.class)
.childHandler(new WebSocketServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(8888).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
Initializer:
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("httpServerCodec",new HttpServerCodec());
pipeline.addLast("streamer",new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler("/websocketpath"));
pipeline.addLast(new TextWebSocketFrameHandler());
}
}
这里有几个handler:
HttpServerCodec
是HttpRequestDecoder
和HttpResponseEncoder
的组合。
ChunkedWriteHandler
支持异步地写出大数据量文件。
HttpObjectAggregator
将HttpMessage
和HttpContent
整合成一个FullHttpRequest
或者FullHttpResponse
。如果我们的传输编码方式是chunked
(一块一块的),我们就不用去担心http消息了,因为HttpObjectAggregator
会帮我们整合好。
WebSocketServerProtocolHandler
是封装websocket协议的handler。
/**
* This handler does all the heavy lifting for you to run a websocket server.
*
* It takes care of websocket handshaking as well as processing of control frames (Close, Ping, Pong). Text and Binary
* data frames are passed to the next handler in the pipeline (implemented by you) for processing.
*/
文档说,WebSocketServerProtocolHandler
会处理Text data frame,我们接下来要用的也是这个frame。
TextWebSocketFrameHandler:
public class TextWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println("receive message: " + msg.text());
ctx.writeAndFlush(new TextWebSocketFrame("server time: " + LocalTime.now()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("TextWebSocketFrameHandler added. " + ctx.channel().id().asLongText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("TextWebSocketFrameHandler removed. " + ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
super.exceptionCaught(ctx, cause);
System.out.println("exception caught!");
ctx.close();
}
}
我们会打印客户端发来的数据并且将服务器的时间返回出去。
客户端我们用html和js来写:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket chat</title>
</head>
<script type="text/javascript">
let socket;
if(window.WebSocket){
socket = new WebSocket("ws://localhost:8888/websocketpath");
socket.onmessage = function (event) {
const content = document.getElementById("responseText");
content.value = content.value + "\n" + event.data;
}
socket.onopen = function (event) {
const content = document.getElementById("responseText");
content.value = "connection open!";
}
socket.onclose = function (event) {
const content = document.getElementById("responseText");
content.value = content.value + "\n" + "connection closed!";
}
}else {
alert("browser doesn't support websocket!")
}
function send(message) {
if(!window.WebSocket){
return;
}
if(socket.readyState == WebSocket.OPEN){
socket.send(message);
}else{
alert("no connection!");
}
}
</script>
<body>
<form onsubmit="return false;">
<h3>client send message</h3>
<textarea name="message" style="width: 400px; height: 200px"></textarea>
<input type="button" value="send" onclick="send(this.form.message.value)">
<h3>server output: </h3>
<textarea id="responseText" style="width: 400px; height: 200px"></textarea>
<input type="button" onclick="javascript: document.getElementById('responseText').value=''" value="clear">
</form>
</body>
</html>
基于websocket协议的地址是这么写的:
ws://localhost:8888/websocketpath
ws指的是协议,后面的websocketpath
与服务端配置的websocketHandler的接收地址是一样的:
pipeline.addLast(new WebSocketServerProtocolHandler("/websocketpath"));
我们在js脚本中对于连接建立、断开、有消息传输都配置了对应的回调函数。
大概的样子是这样的: