概述
http链接分为短链接,长链接,短链接是每次请求都要三次握手才能发送自己的信息。即每一个request对应一个response。长链接是在一定的期限内保持链接。保持TCP连接不断开。客户端与服务器通信,必须要有客户端发起然后服务器返回结果。客户端是主动的,服务器是被动的。
WebSocket主要为了解决客户端发起多个http请求到服务器资源浏览器必须要经过长时间的轮训问题而生的,他实现了多路复用,他是全双工通信。在webSocket协议下客服端和浏览器可以同时发送信息。
建立了WenSocket之后服务器不必在浏览器发送request请求之后才能发送信息到浏览器。这时的服务器已有主动权想什么时候发就可以发送信息到服务器。而且信息当中不必在带有head的部分信息了与http的长链接通信来说,这种方式,不仅能降低服务器的压力。而且信息当中也减少了部分多余的信息。
服务器端
public class MyLongServer {
public static void main(String[] args) throws Exception{
EventLoopGroup bossGroup=new NioEventLoopGroup();
EventLoopGroup workerGroup=new NioEventLoopGroup();
try {
ServerBootstrap serverBootStrap = new ServerBootstrap();
serverBootStrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel socketChannel) throws Exception {
ChannelPipeline pipeline = socketChannel.pipeline();
//因为基于http协议,使用http的编码解码器
pipeline.addLast(new HttpServerCodec());
//是以块方式写,添加ChunkedWrite处理器
pipeline.addLast(new ChunkedWriteHandler());
/**
* 说明:
* 1.http数据在传输过程中是分段的,HttpObjectAggregator,就是可以得到多个段聚合
* 2.这就是为什么,当浏览器发送大量数据 时,就会发出多次http请求
*/
pipeline.addLast(new HttpObjectAggregator(8192));
/**
* 1.对应WebSocket,他的数据是以帧的形式传递的
* 2.可以看到WebSocketFrame 下面有六个子类
* 浏览器发送请求时, ws://localhost:7000/hello 表示请求的url
* WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议,保持长连接
*/
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
//自定义的handler,处理业务逻辑
pipeline.addLast(new MyTaskWebSocketFrameHandler());
}
});
//启动服务器
ChannelFuture channelFuture = serverBootStrap.bind(7000).sync();
channelFuture.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally{
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
自定义一个handler
public class MyTaskWebSocketFrameHandler 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()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//id表示唯一值,LongText是唯一的ShortText 不是唯一的
System.out.println("handler Added被调用"+ctx.channel().id().asLongText());
System.out.println("handler Added被调用"+ctx.channel().id().asShortText());
}
@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();
}
}
Web端
<!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:7000/hello");
//相当于channelReado ,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>