标签:握手 res shu 不同的 htm lang child receive handle
public class WSServer {
public static void main(String[] args) throws InterruptedException {
EventLoopGroup mainGroup = new NioEventLoopGroup();
EventLoopGroup subGroup = new NioEventLoopGroup();
try {
ServerBootstrap server = new ServerBootstrap();
server.group(mainGroup,subGroup)
.channel(NioServerSocketChannel.class)
.childHandler(new WSServerInitializer());
ChannelFuture channelFuture = server.bind(8080).sync();
channelFuture.channel().closeFuture().sync();
} finally {
mainGroup.shutdownGracefully();
subGroup.shutdownGracefully();
}
}
}
public class WSServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
// websocket基于http协议,所以要有http编解码器
pipeline.addLast(new HttpServerCodec());
// 对写大数据流的支持
pipeline.addLast(new ChunkedWriteHandler());
// 对httpMessage进行聚合, 聚合成FullHttpRequest或fullHttpResponse
pipeline.addLast(new HttpObjectAggregator(1024*64));
// ----------------- 以上用于支持HTTP协议------------------
// websocket处理的协议,用于指定给客户端连接访问的路由, : /ws
// 本handler会帮你处理一些繁重的复杂的事
// 会帮你处理握手动作: handshaking(close,ping,pong) ping+pong=心跳
// 对于websocket来说,都是以frames进行传输的,不同的数据类型对应的frames也不同
pipeline.addLast(new WebSocketServerProtocolHandler("/ws"));
// 自定义的handler
pipeline.addLast(new ChatHandler());
}
}
/**
* @author: webin
* @date: 2020/4/4 15:57
* @description: 处理消息的handler
* TextWebSocketFrame: 在netty中,是用于为websocket专门处理文本的对象,frame是消息的载体
* @version: 0.0.1
*/
public class ChatHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {
/** 用于置入和管理所有客户端的channel,把所有的channel都保存到组里面去 */
private static ChannelGroup clients = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
@Override
protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame msg) throws Exception {
// 获取客户端传输过来的消息
String text = msg.text();
System.out.println("接收到的输出: " + text);
for (Channel channel : clients) {
channel.writeAndFlush(
new TextWebSocketFrame("[服务器接收到消息:]"+ LocalDateTime.now()+" 接收到消息,消息内容为: "+text)
);
}
// 和上面作用一样
// clients.writeAndFlush(
// new TextWebSocketFrame("[服务器接收到消息:]"+ LocalDateTime.now()+" 接收到消息,消息内容为: "+text)
// );
}
/**
* 当客户端连接服务端会后
* 获取客户端的channel,并且放到channelGroup中进行管理
* @param ctx
* @throws Exception
*/
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
clients.add(ctx.channel());
}
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
// 当触发handlerRemoved,ChannelGroup会自动移除对应客户端的Channel
clients.remove(ctx.channel());
System.out.println("客户端断开,channel对应的长id:" + ctx.channel().id().asLongText());
System.out.println("客户端断开,channel对应的短id:" + ctx.channel().id().asShortText());
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>发送消息:</div>
<input type="text" id="msgContent">
<input type="button" value="点我发送" onclick="CHAT.chat()">
<div>接收消息:</div>
<div id="receiveMsg" style="background-color: gainsboro"></div>
</body>
<script>
window.CHAT = {
socket: null,
init: function () {
if (window.WebSocket) {
CHAT.socket = new WebSocket("ws://127.0.0.1:8080/ws");
CHAT.socket.onopen = function() {
console.log("连接建立成功...")
}
CHAT.socket.onmessage = function(e) {
console.log("接收到消息: " + e.data)
var receiveMsg = document.getElementById("receiveMsg");
var html = receiveMsg.innerHTML;
receiveMsg.innerHTML = html + "<br/>" + e.data
};
CHAT.socket.close = function() {
console.log("连接关闭...")
};
CHAT.socket.onerror = function () {
console.log("发生错误 ... ")
}
} else {
alert("浏览器不知道WebSocket协议")
}
},
chat: function () {
var msg = document.getElementById("msgContent")
CHAT.socket.send(msg.value)
}
}
CHAT.init();
</script>
</html>
标签:握手 res shu 不同的 htm lang child receive handle
原文地址:https://www.cnblogs.com/smallwolf/p/12632924.html