1)Http协议是无状态的,浏览器和服务器间的请求响应一次,下一次会重新创建连接
2)要求:实现基于WebSocket的长连接的全双工交互
3)改变Http协议多次请求的约束,实现长连接,服务器可以发送消息给浏览器
4)客户端浏览器和服务器端会相互感知,比如服务器关闭了,浏览器会感知,同样浏览器关闭了,服务器会感知
<!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")
//相当于channelRead0, 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(msg) {
if (!window.socket){//判断socket是否创建好
return;
}
if (socket.readyState == WebSocket.OPEN){
//通过socket发送消息
socket.send(msg)
}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>
package com.dd.netty.websocket;
import com.dd.netty.heartbeat.MyServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
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.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
public class MyServer {
private int port ;//监听端口
public MyServer(int port){
this.port = port;
}
public void run() throws InterruptedException {
//创建bossGroup和WrokerGroup
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();//默认cpu核数乘以2个NioEventLoop
try {
ServerBootstrap bootstrap = new ServerBootstrap();
bootstrap.group(bossGroup,workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO))//在boosGroup 增加一个日志处理器
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.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());
//HttpObjectAggregator
/*
1.http数据在传输过程中是分段的,HttpObjectAggregator,就是可以将多个段聚合起来
2.这就是为什么当浏览器发送大量数据时,就会发出多次http请求的原因
*/
pipeline.addLast(new HttpObjectAggregator(8192));
/*
1.对于webSocket,他的数据是以 帧(frame)形式传递
2.可以看到webSocketFrame下面有6个子类
3.浏览器发送请求时地址 ws://localhost:7000/xxx xxx表示请求的uri
4.WebSocketServerProtocolHandler的核心功能为将Http协议升级为ws协议,即webSocket协议,保持长连接
5.是通过一个状态码 101
*/
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
//自定义handler,处理业务逻辑
pipeline.addLast(new MyTestWebSocketFrameHandler());
}
});
System.out.println("Netty服务器启动");
ChannelFuture chanelFuture = bootstrap.bind(port).sync();
//监听关闭事件
chanelFuture.channel().closeFuture().sync();
}finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
public static void main(String[] args) throws InterruptedException {
new MyServer(7000).run();
}
}
package com.dd.netty.websocket;
import com.sun.org.apache.bcel.internal.generic.NEW;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
//TextWebSocketFrame表示一个文本帧(frame)
public class MyTestWebSocketFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
System.out.println("服务器段收到消息"+msg.text());
//回复浏览器
channelHandlerContext.writeAndFlush(new TextWebSocketFrame("服务器时间"+ LocalDateTime.now()+"消息为"+msg.text()));
}
//当web客户端连接后,就会触发该方法
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//id表示唯一的值,
System.out.println("handlerAdded被调用"+ctx.channel().id().asLongText());
//该id不是唯一的值,
System.out.println("handlerAdded被调用"+ctx.channel().id().asShortText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
//id表示唯一的值,
System.out.println("handlerAdded被调用"+ctx.channel().id().asLongText());
//该id不是唯一的值,
System.out.println("handlerAdded被调用"+ctx.channel().id().asShortText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("异常发生" +cause.getMessage());
ctx.close();
}
}