Netty(四)实现WebSocket

Netty之实现WebSocket用户单聊....

简单介绍一下webSocket:

我们一直使用的http协议只能由客户端发起,服务端无法直接进行推送,这就导致了如果服务端有持续的变化客户端想要获知就比较麻烦。WebSocket协议就是为了解决这个问题应运而生。WebSocket协议,客户端和服务端都可以主动的推送消息,可以是文本也可以是二进制数据。而且没有同源策略的限制,不存在跨域问题。协议的标识符就是ws。

WebSocket是H5之后提供的一种网络通讯技术,属于应用层协议。它基于 TCP 传输协议,并复用 HTTP 的握手通道。

 WebSocket帧:

 数据帧:    ---用来传递数据

TextWebSocketFrame:文本帧

BinaryWebSocketFrame:二进制帧 (传输的图片、表情等等

状态帧:    ---检测心跳

PingWebSocketFrame:ping帧(客户端发送ping帧)

PongWebSocketFrame:pong帧(服务端响应pong帧)

CloseWebSocketFrame:关闭帧

开始通讯:::::

依赖这些省略........

服务端


/**
 * @Author Joker
 * @Date 2020/11/16
 * @since 1.8
 */
@Slf4j
public class ServerDemo {
    public static void main(String[] args) {
        EventLoopGroup masterEventLoopGroup = new NioEventLoopGroup();
        EventLoopGroup slaveEventLoopGroup = new NioEventLoopGroup();
        ServerBootstrap bootstrap = new ServerBootstrap();
        ChannelFuture channelFuture = bootstrap.group(masterEventLoopGroup, slaveEventLoopGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer() {
                    @Override
                    protected void initChannel(Channel channel) throws Exception {
                        ChannelPipeline pipeline = channel.pipeline();
                        pipeline.addLast(new HttpServerCodec());
                        pipeline.addLast(new HttpObjectAggregator(1024 * 1024));

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

                        // 在10秒之内收不到消息自动断开
                        pipeline.addLast(new ReadTimeoutHandler(10, TimeUnit.SECONDS));
                        pipeline.addLast(new WebSocketHandler());
                    }
                })
                .bind(8888);
        try {
            channelFuture.sync();
            System.out.println("连接服务器成功...");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

消息处理:

/**
 * @Author Joker
 * @Date 2020/11/16
 * @since 1.8
 */
@Slf4j
public class WebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final String HEART = "ws-heart";

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) throws Exception {
        String text = textWebSocketFrame.text();
        System.out.println("接收到消息: " + text);
        // 判断接收内容是否为心跳值
        if(HEART.equals(text)){
            TextWebSocketFrame socketFrame = new TextWebSocketFrame(HEART);
            channelHandlerContext.writeAndFlush(socketFrame);
        }
    }

    /**
     * 用户加入
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        super.channelRegistered(ctx);
        System.out.println("用户连接");
    }

    /**
     * 用户断开
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        super.channelUnregistered(ctx);
        System.out.println("用户断开");
    }

    /**
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        super.exceptionCaught(ctx, cause);
        System.out.println("用户非正常断开");
    }
}

前端HTML页面:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>websocket</title>
		<script src="./js/jquery-3.4.1.js" type="text/javascript" charset="UTF-8"></script>
	</head>
	<script>
		$(function(){
			var ws = new WebSocket("ws://127.0.0.1:8888");
			var heartTime;
			if(window.WebSocket){
				
				// 连接服务器
				ws.onopen = function(){
					debugger
					var html = "<span style='color:green'>连接服务器成功</span></br>";
					$("#toke").append(html);
                    // 连接成功后发送心跳
					sendHeart();
				}
				
				// 断开服务器
				ws.onclose = function(e){
					clearInterval(heartTime);
					var html = "<span style='color:red'>客户端断开连接</span></br>"
					$("#toke").append(html);
					
				}
				
				// 服务器发生异常
				ws.onerror = function(){
					var html = "<span style='color:red'>服务器异常</span></br>"
					$("#toke").append(html);
				}
				
				ws.onmessage = function(data){
                    // 判断服务端返回的值是否为心跳返回值
					if(data.data == "ws-heart"){
						return;
					}
					var html = "<span>服务器:"+ data.data +"</span></br>"
					$("#toke").append(html);
				}
			} else{
				alert("当前浏览器不支持WebSocket!");
			}
			$("#send").click(function(){
				var msg = $("#con").val();
				ws.send(msg);
				msg = "<span style='color:blue;display:block;text-align:right;margin-right:5px'>"+ msg +"</span></br>";
				var showMsg = $("#toke");
				showMsg.append(msg);
				$("#con").val("");
			});
			
			function sendHeart(){
				heartTime = setInterval(function(){
					ws.send("ws-heart");
				},5000);
			}
		})
	</script>
	<body>
		<div id="toke" style="width: 400px; height: 300px;border: 1px solid #f00;">
			
		</div>
		<input type="text" name="con" id="con" width="100px" />
		<button id="send">发送</button>
	</body>
</html>

三合一,这就是一个简单的webSocket

演示结果::::

如果设置了服务器的回复消息就能看到你发送后服务器给你的回复了。

如有差错!!!请指正,谢谢    

close();

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Netty是一个基于Java的网络编程框架,它提供了一种简单且高性能的方式来实现WebSocket协议。 要使用Netty实现WebSocket,可以按照以下步骤进行操作: 1. 创建一个新的Netty项目,并添加Netty的依赖。 2. 创建一个WebSocket服务器类,该类需要继承自`io.netty.channel.SimpleChannelInboundHandler`。 3. 在服务器类中,重写`channelRead0`方法,处理接收到的WebSocket消息。 4. 在服务器类中,重写`channelActive`和`channelInactive`方法,处理WebSocket连接的打开和关闭事件。 5. 在服务器类中,重写`exceptionCaught`方法,处理异常情况。 6. 创建一个启动类,在其中创建并配置一个`io.netty.bootstrap.ServerBootstrap`实例。 7. 在启动类中,绑定服务器端口并启动服务器。 下面是一个简单的示例代码,演示了如何使用Netty实现WebSocket服务器: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelFuture; import io.netty.channel.ChannelInitializer; import io.netty.channel.EventLoopGroup; 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; public class WebSocketServer { public static void main(String[] args) throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast(new HttpServerCodec()); ch.pipeline().addLast(new HttpObjectAggregator(65536)); ch.pipeline().addLast(new WebSocketServerProtocolHandler("/websocket")); ch.pipeline().addLast(new WebSocketServerHandler()); } }); ChannelFuture future = bootstrap.bind(8080).sync(); future.channel().closeFuture().sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } } ``` 在上面的代码中,`WebSocketServerHandler`是自定义的处理器,用于处理WebSocket消息。你可以根据自己的需求来实现该处理器。 请注意,这只是一个简单的示例,实际的WebSocket服务器可能需要更复杂的处理逻辑。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JokerQGA

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值