netty传递字符串(Server)

配置引导类为

装配ServerBootStrap
            serverBootstrap.group(eventLoopGroup)
            .channel(NioServerSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式
            .localAddress("localhost",port)//设置InetSocketAddress让服务器监听某个端口已等待客户端连接。
            .childHandler(new ChannelInitializer<Channel>() {

             }

等待连接:

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

Handler继承

 ChannelInboundHandlerAdapter

EchoServer类

package server;

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.nio.NioServerSocketChannel;

public class EchoServer{
	private final int port;
	public EchoServer(int port) {
		this.port = port;
	}
	public void start() throws Exception{
		EventLoopGroup eventLoopGroup = null;
		try{
			//创建ServerBootStrap---server端引导类
			ServerBootstrap serverBootstrap = new ServerBootstrap();
			//实例一个eventLoopGroup用来处理事件(线程池)
			eventLoopGroup = new NioEventLoopGroup();
			//装配ServerBootStrap
			serverBootstrap.group(eventLoopGroup)
			.channel(NioServerSocketChannel.class)//指定通道类型为NioServerSocketChannel,一种异步模式
			.localAddress("localhost",port)//设置InetSocketAddress让服务器监听某个端口已等待客户端连接。
			.childHandler(new ChannelInitializer<Channel>() {

				@Override
				protected void initChannel(Channel ch) throws Exception {
					// TODO Auto-generated method stub
					ch.pipeline().addLast(new EchoServerHandler());
				}
			});
			// 最后绑定服务器等待直到绑定完成,调用sync()方法会阻塞直到服务器完成绑定
			// 然后服务器等待通道关闭,因为使用sync(),所以关闭操作也会被阻塞。
			ChannelFuture channelFuture = serverBootstrap.bind().sync();
			System.out.println("开始监听,端口为:" + channelFuture.channel().localAddress());
			channelFuture.channel().closeFuture().sync();
		    }finally{
			eventLoopGroup.shutdownGracefully().sync();
		    }
	}
	public static void main(String[] args) throws Exception {
		new EchoServer(20000).start();
	}
}

EchoServerHandler类

package server;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class EchoServerHandler extends ChannelInboundHandlerAdapter{
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		System.out.println("server 开始读取数据");
		ByteBuf buf = (ByteBuf)msg;
		byte[] req = new byte[buf.readableBytes()];
		buf.readBytes(req);
		String body = new String(req,"UTF-8");
		System.out.println("接受客户端的数据:"+body);
		//发送数据
		System.out.println("向客户端发送数据");
		String currentTime = new Date(System.currentTimeMillis()).toString();
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp);
	}
	
	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("服务端发送数据完毕");
		ctx.flush();
	}
	
	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		cause.printStackTrace();
		ctx.close();
	}
	
}

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Spring Boot和Netty来实现对Json字符串的处理。首先,你需要在Spring Boot项目中集成Netty依赖。可以在你的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.52.Final</version> </dependency> ``` 接下来,你可以创建一个Netty服务器来处理Json字符串。这里是一个简单的示例: ```java import io.netty.bootstrap.ServerBootstrap; import io.netty.channel.ChannelInitializer; import io.netty.channel.ChannelOption; 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.LineBasedFrameDecoder; import io.netty.handler.codec.string.StringDecoder; import io.netty.handler.codec.string.StringEncoder; public class JsonServer { private int port; public JsonServer(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 LineBasedFrameDecoder(1024)); ch.pipeline().addLast(new StringDecoder()); ch.pipeline().addLast(new StringEncoder()); ch.pipeline().addLast(new JsonHandler()); } }) .option(ChannelOption.SO_BACKLOG, 128) .childOption(ChannelOption.SO_KEEPALIVE, true); System.out.println("Server started on port " + port); b.bind(port).sync().channel().closeFuture().sync(); } finally { workerGroup.shutdownGracefully(); bossGroup.shutdownGracefully(); } } public static void main(String[] args) throws Exception { int port = 8080; new JsonServer(port).run(); } } ``` 在上面的示例中,我们创建了一个简单的Netty服务器,并使用`StringDecoder`和`StringEncoder`来处理字符串的编码和解码。`JsonHandler`是自定义的处理器,你可以在其中实现对Json字符串的处理逻辑。 现在你可以运行这个服务器,并通过发送Json字符串与服务器进行交互。你可以根据自己的需求在`JsonHandler`中添加相应的处理逻辑。 需要注意的是,这只是一个简单的示例,你可能需要根据具体的业务需求进行适当的修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值