https://gitee.com/henan000/netty
WebSocketServerProtocolHandler主要是靠是这个类 去将http转换成ws
通过一个状态来切换 101
![](https://img.haomeiwen.com/i7616246/ebdf8b2c1c73f2c2.png)
package com.whn.text.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.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 WebsocketServer {
public static void main(String[] args) throws InterruptedException {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workGroup).
channel(NioServerSocketChannel.class).
handler(new LoggingHandler(LogLevel.INFO)).
childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline channelPipeline = ch.pipeline();
channelPipeline.addLast(new HttpServerCodec());
channelPipeline.addLast(new ChunkedWriteHandler());
channelPipeline.addLast(new HttpObjectAggregator(8192));
//ws://localhost:7000/test
channelPipeline.addLast(new WebSocketServerProtocolHandler("/test"));
channelPipeline.addLast(new WebsocketHandler());
}
});
System.out.println("服务端准备完毕。。。");
ChannelFuture channelFuture = serverBootstrap.bind(7000).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
package com.whn.text.websocket;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import java.time.LocalDateTime;
public class WebsocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
System.out.println("服务器收到消息:" + msg.text());
ctx.writeAndFlush(new TextWebSocketFrame("服务器时间" + LocalDateTime.now() + "::" + msg.text()));
}
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
System.out.println("handlerAdded 被调用" + ctx.channel().id().asLongText());
}
@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 {
ctx.close();
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
var socket;
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:7000/test");
socket.onmessage = function (ev) {
var r = document.getElementById('responseText');
r.value = r.value + "\n" + ev.data;
}
socket.onopen = function (ev) {
var r = document.getElementById('responseText');
r.value = "连接开启。。。"
}
socket.onclose = function (ev) {
var r = document.getElementById('responseText');
r.value = r.value + "\n" + "连接关闭。。。"
}
} else {
alert("当前浏览器不支持websocket")
}
function send(msg) {
if (!window.socket) {
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(msg)
} else {
alert("连接没开启");
}
}
</script>
<form onsubmit="return false">
<textarea name="msg" style="height: 100px;width: 100px"></textarea>
<input type="button" value="发送消息" onclick="send(this.form.msg.value)">
<textarea id="responseText" style="height: 100px;width: 100px"></textarea>
<input type="button" value="请空内容" onclick="document.getElementById('responseText').value=''">
</form>
</body>
</html>
网友评论