netty-netty基本使用

netty-netty基本使用

摘自<netty权威r指南>

编写netty服务器和客户端三部曲:

  • 绑定Group(EventLoopGroup,即一组EventLoop集合,可以理解成socket线程组)
  • 声明Channel
  • 指定ChannelHandler

服务器端

public class TimeServerHandler extends ChannelInboundHandlerAdapter {


	@Override
	public void channelRead(ChannelHandlerContext ctx, 
										Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()];

		buf.readBytes(req);
		String body = new String(req, "UTF-8");
		System.out.println("time server recv[x]: "+ body);

		String currentTime = "time".equals(body) ?
             new Date(System.currentTimeMillis()).toString() : "bad time";
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp);
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx)
                                                     throws Exception {
//		ctx.flush();
		ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
				.addListener(ChannelFutureListener.CLOSE);
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, 
                                    Throwable cause) throws Exception {
		ctx.close();
	}
}

服务器启动类:

public class TimeServer {

	public static void main(String[] args) {
		int port = 8080;
		new TimeServer().bind(port);
	}

	public void bind(int port) {
		EventLoopGroup bossGroup = new NioEventLoopGroup();
		EventLoopGroup workGroup = new NioEventLoopGroup();
		try {

			ServerBootstrap serverBootstrap = new ServerBootstrap();
			serverBootstrap.group(bossGroup, workGroup)
					.channel(NioServerSocketChannel.class)
					.option(ChannelOption.SO_BACKLOG, 1024)
					.childHandler(new ChildChannelHandler());
			//阻塞到启动成功
//			ChannelFuture future = serverBootstrap.bind(port).sync();
			ChannelFuture future = serverBootstrap.bind(port);
			future.addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future)
                                                         throws Exception {
					if (future.isSuccess()){
						System.out.println("server started success...");
					}else {
						System.out.println("server started failed...");
						future.cause().printStackTrace();
					}
				}
			});
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			bossGroup.shutdownGracefully();
			workGroup.shutdownGracefully();
		}
	}

}

客户端


public class TimeClientHandler extends ChannelInboundHandlerAdapter {

	private final ByteBuf firstMsg;

	public TimeClientHandler() {
		String time = "time";
		firstMsg = Unpooled.copiedBuffer(time.getBytes());
	}

	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		ctx.writeAndFlush(firstMsg);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx,
                                         Object msg) throws Exception {
		ByteBuf buf = (ByteBuf)msg;
		byte[] bytes = new byte[buf.readableBytes()];
		buf.readBytes(bytes);
		String body = new String(bytes,"utf-8");
		System.out.println("now is :"+ body);

	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, 
                                    Throwable cause) throws Exception {
		ctx.close();
	}
}

客户端启动类:

public class TimeClient {

	public static void main(String[] args) throws InterruptedException {
		int port = 8080;
		String host = "127.0.0.1";
		new TimeClient().connect(port, host);
	}
	public void connect(int port, String host) throws InterruptedException {
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			Bootstrap bootstrap = new Bootstrap();
			bootstrap.group(group).channel(NioSocketChannel.class)
					.option(ChannelOption.TCP_NODELAY,true)
					.handler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel ch) 
															throws Exception {
							ch.pipeline().addLast(new TimeClientHandler());
						}
					});
			//阻塞到连接成功
//			ChannelFuture future= bootstrap.connect(host, port).sync();
			ChannelFuture future= bootstrap.connect(host, port);
			future.addListener(new ChannelFutureListener() {
				@Override
				public void operationComplete(ChannelFuture future) 
														throws Exception {
					if (future.isSuccess()){
						System.out.println("client established success...");
					}else {
						System.out.println("client established failed...");
						future.cause().printStackTrace();
					}
				}
			});
			future.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully();

		}
	}
}

运行结果

1.服务器端运行结果:

server started success...
time server recv[x]: time

2.客户端运行结果:

client established success...
now is :Mon Feb 03 15:51:51 CST 2020

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Netty-socketio是一个用于构建实时通信应用程序的开源框架。它基于Netty框架,通过使用WebSocket协议来实现异步、高性能的网络通信。Netty-socketio具有以下特点: 1. 强大的异步处理能力:Netty-socketio采用事件驱动的方式处理客户端请求,能够高效地处理大量并发连接。 2. 完善的消息传递机制:Netty-socketio提供了灵活的消息传递方式,支持广播、点对点、房间等不同的消息发送方式,满足不同场景下的通信需求。 3. 多协议支持:Netty-socketio不仅支持WebSocket协议,还支持其他常用的协议,如TCP、HTTP等,便于与现有的系统集成。 4. 可扩展性强:Netty-socketio提供了丰富的拓展接口,用户可以根据自己的需求定制和扩展框架的功能。 5. 易于使用Netty-socketio提供了简洁的API和丰富的文档,可以快速上手使用,并提供了相应的示例代码,方便开发者学习和理解。 对于客服应用来说,Netty-socketio作为一个实时通信框架,可以用于构建在线客服聊天系统。通过使用Netty-socketio,我们可以实现客户与客服人员之间的实时消息传递,支持文字、图片、文件等多种类型的消息。客户可以通过网页或移动端应用与客服人员进行沟通,实时解决问题,提升用户体验。 Netty-socketio提供了强大的异步处理能力和全双工通信机制,能够处理大量并发连接,并保持连接的稳定性和可靠性。同时,它的多协议支持和可扩展性强的特点,使得我们可以根据自己的业务需求进行定制和拓展,满足不同客服场景下的通信需求。 总之,Netty-socketio作为一个强大的实时通信框架,为客服应用提供了一种高效、稳定的解决方案,帮助企业构建更好的客服系统,并提升客户的满意度。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值