Netty通过WebSocket编程实现服务器和客户端长连接
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了Netty通过WebSocket编程实现服务器和客户端长连接,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3871字,纯文字阅读大概需要6分钟。
内容图文
服务器端
public class MyServer {
public static void main(String[] args) throws Exception {
NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workerGroup = new NioEventLoopGroup();
try {
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class)
.handler(new LoggingHandler(LogLevel.INFO)) //在bossGroup增加一个日志处理器
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
//基于http协议、使用http的编码和解码器
pipeline.addLast(new HttpServerCodec());
//以块方式写、添加ChunkedWriteHandler处理器
pipeline.addLast(new ChunkedWriteHandler());
/**
* 因为http协议传输过程中是分段的、HttpObjectAggregator可以将多个段进行聚合
* 所以浏览器发送大量数据时、会发出多次http请求
*/
pipeline.addLast(new HttpObjectAggregator(8192));
/**
* 对应WebSocket ,他的数据以帧方式传递
* WebSocketServer下面有六个子类
* 浏览器请求时 ws://localhost:9999/hello 表示请求的uri
* WebSocketServerProtocolHandler 核心功能是将http协议升级为ws协议,保持长连接
*/
pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
//自定义handler,处理业务逻辑
pipeline.addLast(new MyTextWebSocketFrameHandler());
}
});
ChannelFuture channelFuture = serverBootstrap.bind(9999).sync();
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
自定义Handler
public class MyTextWebSocketFrameHandler 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() + " " + msg.text()));
}
//当web客户端连接后、触发方法
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
//id表示唯一的标识,LongText是唯一的 ShortText不是唯一的
System.out.println("handlerAdded被调用了"+ctx.channel().id().asLongText());
System.out.println("handlerAdded被调用了"+ctx.channel().id().asShortText());
super.handlerAdded(ctx);
}
@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("异常发生" + cause.getMessage());
ctx.close(); //关闭连接
}
}
前端页面代码
<!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:9999/hello");
//相当于channelRead 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(message) {
if (!window.socket) { //判断socket是否建立好
return;
}
if (socket.readyState == WebSocket.OPEN) {
//通过socket发送消息
socket.send(message);
} 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>
内容总结
以上是互联网集市为您收集整理的Netty通过WebSocket编程实现服务器和客户端长连接全部内容,希望文章能够帮你解决Netty通过WebSocket编程实现服务器和客户端长连接所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。