Study this matter, don’t care if someone urges you, the most important thing is that you have no consciousness and perseverance.
During review, I will record the process of self-study in the form of notes.
Some pictures of this article come from video notes!! Not my own drawing!!
The Http protocol is stateless. A request between the browser and the server is responded to once and the connection is re-created the next time.
The full-duplex websocket-based long-connection interaction changes the restriction of multiple Http requests. When a long-connection is implemented, the server can send a message to the browser. The client and server can sense each other
server
package netty.netty.websocket; import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelPipeline; import io.netty.channel.EventLoopGroup; 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; import io.netty.handler.timeout.IdleStateHandler; import java.util.concurrent.TimeUnit; Public class MyServer {public static void main(String[] args) throws Exception{// Create two thread groups EventLoopGroup bossGroup = new NioEventLoopGroup(1); EventLoopGroup workerGroup = new NioEventLoopGroup(); //8 NioEventLoop try {ServerBootstrap ServerBootstrap = new ServerBootstrap(); serverBootstrap.group(bossGroup, workerGroup); serverBootstrap.channel(NioServerSocketChannel.class); serverBootstrap.handler(new LoggingHandler(LogLevel.INFO)); serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); // Because of the HTTP protocol, use HTTP encoding and decoder pipeline. AddLast (new HttpServerCodec()); // Add ChunkedWriteHandler to pipeline.addlast (new ChunkedWriteHandler()); /* Note 1. HTTP data is segmted during transmission. HttpObjectAggregator can aggregate multiple segments. This is why, when the browser sends a lot of data, it makes multiple HTTP requests */ pipeline.addlast (new HttpObjectAggregator(8192)); /* Description 1. Corresponding to the Websocket, its data is transmitted in the form of frames. Can see WebSocketFrame has six children below 3. When the browser requests the ws: / / localhost: 7000 / hello said request uri 4. WebSocketServerProtocolHandler core function is to Upgrade HTTP to WS and maintain long Connections 5. Is through a status code of 101 * / pipeline in addLast (new WebSocketServerProtocolHandler ("/hello2")); / / custom handler, pipeline processing business logic. The addLast (new MyTextWebSocketFrameHandler ()); }}); ChannelFuture = serverbootstrap.bind (7000).sync(); ChannelFuture = serverbootstrap.bind (7000).sync(); channelFuture.channel().closeFuture().sync(); }finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); }}}Copy the code
handler
package netty.netty.websocket; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import io.netty.handler.codec.http.websocketx.TextWebSocketFrame; import java.time.LocalDateTime; // TextWebSocketFrame, Said a text frame (frame) public class MyTextWebSocketFrameHandler extends SimpleChannelInboundHandler < TextWebSocketFrame > { @Override protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception { System.out.println("Server received message"+ msg.text()); Ctx.channel ().writeAndFlush(new TextWebSocketFrame()"Server time" + LocalDateTime.now() + ""+ msg.text())); } @override public void handlerAdded(ChannelHandlerContext CTX) throws Exception {// Id indicates a unique value. LongText is unique ShortText is not unique System.out.println("HandlerAdded called" + ctx.channel().id().asLongText());
System.out.println("HandlerAdded called" + ctx.channel().id().asShortText());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
System.out.println("HandlerRemoved is invoked." + ctx.channel().id().asLongText());
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
System.out.println("Abnormal occurrence"+ cause.getMessage()); ctx.close(); // Close the connection}}Copy the code
html
<! DOCTYPE html> <html lang="en">
<head>
<meta charset="UTF-8"> <title>Title</title> </head> <body> <script> var socket; // Check whether the current browser supports Websocketif(window.WebSocket) {
//go on
socket = new WebSocket("ws://localhost:7000/hello2"); // equivalent to channelReado, ev receives the message socket. onMessage = from the serverfunction (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n"+ ev.data; } // equivalent to connection open (sense connection open) socket.onopen =function (ev) {
var rt = document.getElementById("responseText");
rt.value = "Connection opened..."} // Equivalent to connection closed (sense connection closed) socket.onclose =function (ev) {
var rt = document.getElementById("responseText");
rt.value = rt.value + "\n" + "Connection closed..."}}else {
alert("Current browser does not support Websocket"} // Send a message to the serverfunction send(message) {
if(! Window.socket) {// Check whether the socket is createdreturn;
}
if(socket.readyState == websocket.open) {// Send a message through the socket socket.send(message)}else {
alert("Connection not open");
}
}
</script>
<form onsubmit="return false">
<textarea name="message" style="height: 300px; width: 300px"></textarea>
<input type="button" value="News in progress" onclick="send(this.form.message.value)">
<textarea id="responseText" style="height: 300px; width: 300px"></textarea>
<input type="button" value="Clear the contents" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>
Copy the code