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();
}
}