netty长连接

博客主要提及使用HTML5代码实现客户端,涉及WebSocket和Netty长连接相关内容,聚焦于信息技术领域中前端开发与网络连接方面。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

MyServer
package com.wq.nettylongconnection;

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;

import java.net.InetSocketAddress;

public class MyServer {
    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup,workerGroup).
                            handler(new LoggingHandler(LogLevel.INFO)).
                            channel(NioServerSocketChannel.class).
                            childHandler(new WebSocketInitializer());
            ChannelFuture channelFuture =serverBootstrap.bind(new InetSocketAddress(8899)).sync();
            channelFuture.channel().closeFuture().sync();
        }catch(Exception e){
            e.printStackTrace();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
WebSocketInitializer
package com.wq.nettylongconnection;

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 WebSocketInitializer 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 WebSocketFrameHandler());
    }
}
WebSocketFrameHandler
package com.wq.nettylongconnection;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

import java.time.LocalDateTime;

public class WebSocketFrameHandler 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();
    }
}

html5代码客户端

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket</title>
</head>
<body>
<script type="text/javascript">

    var socket;
    if(window.WebSocket){
        socket = new WebSocket("ws://localhost:8899/ws");
        socket.onmessage = function(event){
           var ta = document.getElementById("responseText");
           ta.value = ta.value+"\n"+event.data;

        }
        socket.onopen = function (event) {
            var ta = document.getElementById("responseText");
            ta.value = "连接开启!";
        }
        socket.onclose = function (ev) {
            var ta = document.getElementById("responseText");
            ta.value = ta.value+"\n"+"连接关闭!";
        }
    }else{
        alert("浏览器不支持WebSocket!");
    }
    function sendMessage(message) {
        if(!window.WebSocket){
            return;
        }
        if(socket.readyState==WebSocket.OPEN){
            socket.send(message);
        }else{
            alert("连接尚未开启");
        }
    }
</script>

<form onsubmit="return false;">

    <textarea name="message" style="width:400px;height:200px;"></textarea>
    <input type="button" value="发送数据" onclick="sendMessage(this.form.message.value)">

    <textarea id="responseText" style="width: 400px;height: 300px;"></textarea>
    <input type="button" value="清空内容" onclick="javascript:document.getElementById('responseText').value=''" >
</form>

</body>
</html>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值