概述
netty支持websocket,下面的demo用一个html作为客户端,对服务端发起websocket请求。
服务端代码
package websocket.server;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
public class WebSocketServer {
public static void main(String[] args)
throws InterruptedException {
EventLoopGroup parentGroup =
new NioEventLoopGroup();
EventLoopGroup childGroup =
new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap =
new ServerBootstrap();
serverBootstrap.group(parentGroup, childGroup)
.channel(NioServerSocketChannel.class)
.handler(
new LoggingHandler(LogLevel.INFO))
.childHandler(
new WebSocketServerInitializer());
ChannelFuture channelFuture = serverBootstrap.bind(
8899).sync();
channelFuture.channel().closeFuture().sync();
}
finally {
parentGroup.shutdownGracefully();
childGroup.shutdownGracefully();
}
}
}
package websocket.server;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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.stream.ChunkedWriteHandler;
public class WebSocketServerInitializer extends ChannelInitializer<SocketChannel>{
@Override
protected void initChannel(SocketChannel ch)
throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast(
new HttpServerCodec());
pipeline.addLast(
new ChunkedWriteHandler());
pipeline.addLast(
new HttpObjectAggregator(
8192));
pipeline.addLast(
new WebSocketServerProtocolHandler(
"/ws"));
pipeline.addLast(
new WebSocketServerHandler());
}
}
package websocket.server;
import java.time.LocalDateTime;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
public class WebSocketServerHandler extends SimpleChannelInboundHandler<TextWebSocketFrame>{
@Override
protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg)
throws Exception {
System.out.println(
"收到的消息:"+msg.text());
ctx.channel().writeAndFlush(
new TextWebSocketFrame(
"服务器时间:"+LocalDateTime.now()));
}
@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 {
System.out.println(
"异常发生");
ctx.close();
}
}
客户端代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>websocket 客户端
</title>
</head>
<body>
<script type="application/javascript">
var socket;
if (window.WebSocket) {
socket = new WebSocket("ws://localhost:8899/ws");
socket.onmessage = function (event) {
var responseContent = document.getElementById("responseText");
responseContent.value = responseContent.value + "\n" + event.data;
};
socket.onopen = function (event) {
var responseContent = document.getElementById("responseText");
responseContent.value = "连接建立了";
};
socket.onclose = function (event) {
var responseContent = document.getElementById("responseText");
responseContent.value = responseContent.value + "\n" + "连接断开了";
}
}
else {
alert('浏览器不支持websocket');
}
function send(message) {
if (!window.WebSocket){
return;
}
if (socket.readyState == WebSocket.OPEN) {
socket.send(message);
}
else {
alert('连接还未建立');
}
}
</script>
<form onsubmit="return false;">
<textarea id="messageId" name="message" style="width: 400px; height: 200px"></textarea>
<input type="button" value="发送按钮" onclick="send(document.getElementById('messageId').value)">
<h3>服务端输出:
</h3>
<textarea id="responseText" name="message" style="width: 400px; height: 300px"></textarea>
</form>
</body>
</html>
csdn code 路径
这个项目的源代码放置在csdn code上,欢迎访问。
netty_study
Sam哥哥
认证博客专家
项目管理
团队管理
总结和思考
喜欢研究和思考关于管理、领导力,流程、文化、人、效率,沟通、成本、执行的东西,因为这些因素跟【能否把事情真正做好】强相关。