java web tcp 长连接_netty通过websocket实现服务器与客户端的长连接

本文展示了如何利用Java的Netty框架和WebSocket协议创建一个服务器,以实现服务器与客户端之间的长连接。通过ServerBootstrap配置服务器端的NioEventLoopGroup、ChannelOption和处理器链,包括HttpServerCodec、WebSocketServerProtocolHandler以及自定义的ServerHandler。在ServerHandler中,处理接收到的消息并回应客户端。同时提供了一个简单的WebSocket HTML客户端代码片段,用于展示如何建立连接、接收和发送消息。
摘要由CSDN通过智能技术生成

server端代码import com.chinadaas.bio.chinadaasbio.webSocket.handler.ServerHandler;

import io.netty.bootstrap.ServerBootstrap;

import io.netty.channel.ChannelFuture;

import io.netty.channel.ChannelInitializer;

import io.netty.channel.ChannelOption;

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 Server {

public static void main(String[] args) throws Exception {

NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);

NioEventLoopGroup workerGroup = new NioEventLoopGroup();

try {

ServerBootstrap serverBootstrap = new ServerBootstrap();

serverBootstrap.group(boosGroup, workerGroup);

serverBootstrap.channel(NioServerSocketChannel.class);

serverBootstrap.option(ChannelOption.SO_BACKLOG, 128);

serverBootstrap.option(ChannelOption.SO_KEEPALIVE, true);

serverBootstrap.handler(new LoggingHandler(LogLevel.INFO));

serverBootstrap.childHandler(new ChannelInitializer() {

@Override

protected void initChannel(SocketChannel socketChannel) throws Exception {

ChannelPipeline pipeline = socketChannel.pipeline();

// 因为是基于http的 所以使用http的编码和解析器

pipeline.addLast(new HttpServerCodec());

// 是以块方式写,添加ChunkWriteHandler() 处理器

pipeline.addLast(new ChunkedWriteHandler());

// http在传输过程中是分段的,这就是为什么当浏览器发送大量数据的时候,会发出多次http请求

pipeline.addLast(new HttpObjectAggregator(8192));

// 1:对应websocket 他的数据是以帧的形式传递

// 2: WebSocketServerProtocolHandler 功能是将http协议升级为ws协议,保持一个长连接

pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));

// 添加自定义的handler

pipeline.addLast(new ServerHandler());

}

});

ChannelFuture channelFuture = serverBootstrap.bind(8886).sync();

channelFuture.channel().closeFuture().sync();

} finally {

boosGroup.shutdownGracefully();

workerGroup.shutdownGracefully();

}

}

}

ServerHandler 代码import io.netty.channel.ChannelHandlerContext;

import io.netty.channel.SimpleChannelInboundHandler;

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

public class ServerHandler extends SimpleChannelInboundHandler {

@Override

protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {

System.out.println("服务器收到消息:" + textWebSocketFrame.text());

channelHandlerContext.channel().writeAndFlush(new TextWebSocketFrame("服务器时间" + LocalDateTime.now() + " " + textWebSocketFrame.text()));

}

@Override

public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {

System.out.println(ctx.channel().remoteAddress()+"断开了连接");

}

}

websocket html 代码

Title

var socket;

if (window.WebSocket) {

socket = new WebSocket("ws://localhost:8886/hello")

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) {

return;

}

if (socket.readyState == WebSocket.OPEN) {

socket.send(message);

} else {

alert("连接没有开启...")

}

}

欢迎大家前来讨论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值