Netty-简单示例

归档

JDK-示例

  • ref: https://github.com/zengxf/small-frame-demo/tree/master/jdk-demo/simple-demo/src/main/java/test/socket/nio

Netty-示例

  • codec 模块下创建用例
    • 包名:mytest

服务端

package io.netty.handler.codec.mytest;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

import java.net.InetSocketAddress;

public class MyServerTest {
    static int PORT = 8899;

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup elg = new NioEventLoopGroup(2);
        ServerBootstrap sb = new ServerBootstrap();
        sb.group(elg);
        sb.channel(NioServerSocketChannel.class);       // 设置 NIO 类型的 Channel
        sb.localAddress(new InetSocketAddress(PORT));   // 设置监听端口

        // 装配流水线
        sb.childHandler(new ChannelInitializer<SocketChannel>() {
            protected void initChannel(SocketChannel sc) { // 有连接到达时就会创建 Channel
                sc.pipeline().addLast("toStr", new StringDecoder());    // 接收时用解码器
                sc.pipeline().addLast("test", new TestHandler());       // sign_demo_010
            }
        });
        ChannelFuture cf = sb.bind().sync(); // sign_demo_001
        System.out.println("启动完成 -------------");
        cf.channel().closeFuture().sync();
        System.out.println("关闭完成 -------------");
        elg.shutdownGracefully();
    }

    static class TestHandler extends ChannelInboundHandlerAdapter {
        @Override // sign_demo_020
        public void handlerAdded(ChannelHandlerContext ctx) throws Exception {
            new RuntimeException("栈跟踪-处理器被添加").printStackTrace();
            super.handlerAdded(ctx);
        }

        @Override // sign_demo_021
        public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
            new RuntimeException("栈跟踪-处理器被注册").printStackTrace();
            super.channelRegistered(ctx);
        }

        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            System.out.println("读取消息:" + msg);
            super.channelRead(ctx, msg);
        }
    }
}

客户端

package io.netty.handler.codec.mytest;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.time.LocalTime;

public class MyClientTest {
    public static void main(String[] args) {
        EventLoopGroup elg = new NioEventLoopGroup(1);
        Bootstrap cb = new Bootstrap();
        cb.group(elg);
        cb.channel(NioSocketChannel.class);
        cb.remoteAddress("localhost", MyServerTest.PORT);

        // 设置通道初始化
        cb.handler(new ChannelInitializer<SocketChannel>() {
            public void initChannel(SocketChannel ch) {
                ch.pipeline().addLast("toByte", new StringEncoder()); // 发送时用编码器
            }
        });
        System.out.println("客户端开始连接...");
        ChannelFuture cf = cb.connect(); // 异步发起连接

        cf.addListener((ChannelFuture f) -> {
            if (f.isSuccess()) {
                System.out.println("连接成功!");
                String msg = "中-Test 123..." + LocalTime.now();
                Channel channel = f.channel();
                channel.write(msg); // sign_u_001 写入消息
                System.out.println("发送消息:" + msg);
                channel.flush();    // sign_u_002 推送消息
                channel.close().sync();     // 关闭 channel
                elg.shutdownGracefully();   // 关闭线程池(这样才会退出)
            } else {
                System.out.println("连接还未成功!");
            }
        });
    }
}
  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netty是一个高性能的网络编程框架,而websocket是一种在Web应用中实现双向通信的协议。Netty可以用来实现WebSocket服务器,从而让Web应用能够与客户端建立持久化的连接,并进行双向通信。 要在Netty中实现WebSocket服务器,你可以使用Netty提供的WebSocket协议的支持。下面是一个简单示例代码: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.Channel; 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 { private final int port; public WebSocketServer(int port) { this.port = port; } public void run() throws Exception { EventLoopGroup bossGroup = new NioEventLoopGroup(); EventLoopGroup workerGroup = new NioEventLoopGroup(); try { ServerBootstrap b = new ServerBootstrap(); b.group(bossGroup, workerGroup) .channel(NioServerSocketChannel.class) .childHandler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ch.pipeline().addLast( new HttpServerCodec(), new HttpObjectAggregator(65536), new WebSocketServerProtocolHandler("/websocket"), new WebSocketServerHandler()); } }); Channel ch = b.bind(port).sync().channel(); System.out.println("WebSocket Server started at port " + port + "."); System.out.println("Open your browser and navigate to http://localhost:" + port + "/"); ChannelFuture future = ch.closeFuture(); future.sync(); } finally { bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; if (args.length > 0) { port = Integer.parseInt(args[0]); } new WebSocketServer(port).run(); } } ``` 在上面的示例代码中,我们创建了一个WebSocket服务器,并将其绑定到指定的端口上。通过`WebSocketServerHandler`类来处理客户端和服务器之间的WebSocket通信。 你可以根据自己的需求,定制`WebSocketServerHandler`来处理不同的业务逻辑。例如,你可以在`channelRead()`方法中处理接收到的WebSocket消息,然后通过`channel().writeAndFlush()`方法发送响应消息给客户端。 希望以上信息能对你有所帮助!如果你还有其他问题,请继续提问。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值