Java NIO框架Netty教程(三) 字符串消息收发

了解了Netty的基本概念(http://m15047453160.iteye.com/blog/2150214),开发起来应该会顺手很多。 在“Hello World(http://m15047453160.iteye.com/blog/2150203)”代码中,我们只是在完成绑定的时候,在各自的本地打印了简单的信息,并没有客户端和服务端的消息传递。这个肯定是最基本的功能。在上代码之前,先补充一个Netty中重要的概念,ChannelBuffer.


ChannelBuffer



 

 

Netty中的消息传递,都必须以字节的形式,以ChannelBuffer为载体传递。简单的说,就是你想直接写个字符串过去,对不起,抛异常。虽然,Netty定义的writer的接口参数是Object的,这可能也是会给新上手的朋友容易造成误会的地方。Netty源码中,是这样判断的:

	SendBuffer acquire(Object message) {
		if (message instanceof ChannelBuffer) {
			return acquire((ChannelBuffer) message);
		} else if (message instanceof FileRegion) {
			return acquire((FileRegion) message);
		}
		throw new IllegalArgumentException(
		"unsupported message type: " + message.getClass());
	}

 所以,我们要想传递字符串,那么就必须转换成ChannelBuffer。明确了这一点,接下来我们上代码:

  服务端代码:

 

import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ServerBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.MessageEvent;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;

public class MessageServer {
	public static void main(String args[]) {
		// Server服务启动器
		ServerBootstrap bootstrap = new ServerBootstrap(
				new NioServerSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		// 设置一个处理客户端消息和各种消息事件的类(Handler)
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new MessageServerHandler());
			}
		});
		// 开放8000端口供客户端访问。
		bootstrap.bind(new InetSocketAddress(8000));
	}

	private static class MessageServerHandler extends SimpleChannelHandler {
		/**
		 * 用户接受客户端发来的消息,在有客户端消息到达时触发
		 */
		@Override
		public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
			ChannelBuffer buffer = (ChannelBuffer) e.getMessage();
			System.out.println(buffer.toString(Charset.defaultCharset()));
		}
	}
}

   客户端代码:

 

import java.net.InetSocketAddress;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.ChannelStateEvent;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.SimpleChannelHandler;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;

public class MessageClient {

	public static void main(String args[]) {
		// Client服务启动器
		ClientBootstrap bootstrap = new ClientBootstrap(
				new NioClientSocketChannelFactory(
						Executors.newCachedThreadPool(),
						Executors.newCachedThreadPool()));
		// 设置一个处理服务端消息和各种消息事件的类(Handler)
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				return Channels.pipeline(new MessageClientHandler());
			}
		});
		// 连接到本地的8000端口的服务端
		bootstrap.connect(new InetSocketAddress("127.0.0.1", 8000));
	}

	private static class MessageClientHandler extends SimpleChannelHandler {
		/**
		 * 当绑定到服务端的时候触发,给服务端发消息。
		 */
		public void channelConnected(ChannelHandlerContext ctx,
				ChannelStateEvent e) {
			// 将字符串,构造成ChannelBuffer,传递给服务端
			String msg = "Hello, I'm client.";
			ChannelBuffer buffer = ChannelBuffers.buffer(msg.length());
			buffer.writeBytes(msg.getBytes());
			e.getChannel().write(buffer);
		}
	}
}

 与 “Hello World(http://m15047453160.iteye.com/blog/2150203)” 样例代码不同的是,客户端在channel连通后,不是在本地打印,而是将消息转换成ChannelBuffer传递给服务端,服务端接受到ChannelBuffer后,解码成字符串打印出来。


同时,通过对比可以发现,变动的只是Handler里的代码,启动服务和绑定服务的代码没有变化,也就是我们在概念介绍里提到了,关注Handler,在Handler里处理我们自己的业务。所以,以后我们会只给出业务中关键代码,不会在上重复的代码:)

由于在Netty中消息的收发全依赖于ChannelBuffer,所以,下一章我们将会详细的介绍ChannelBuffer的使用。我们一起学习。

<think>我们正在构建一个Spring Boot应用,其中需要Netty作为客户端来发送字符串接收响应。根据引用内容,我们主要关注如何配置Netty客户端以及如何发送和接收消息。 步骤: 1. 添加依赖:在pom.xml中添加Netty依赖。 2. 配置Netty客户端:创建Netty客户端的启动类,配置连接服务器的地址和端口。 3. 定义客户端处理器:处理发送消息接收响应的逻辑。 4. 在Spring Boot中集成:通过一个Service或Component来调用Netty客户端发送消息。 注意:引用[3]中提到了服务端的连接处理,但我们现在需要的是客户端。 具体实现如下: 1. 添加依赖(Maven): ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.68.Final</version> <!-- 请使用最新稳定版本 --> </dependency> ``` 2. 创建Netty客户端处理器: 我们需要创建一个ChannelInboundHandlerAdapter来处理消息的发送和接收。 3. 启动Netty客户端: 在Spring Boot中,我们可以使用CommandLineRunner或ApplicationRunner在应用启动后启动Netty客户端,或者通过一个Service来按需启动。 4. 发送消息接收响应: 我们将实现一个简单的客户端,连接到服务器,发送字符串,然后等待响应并关闭连接。 由于Netty是异步的,我们需要一种方式等待响应。这里我们可以使用CompletableFuture。 示例代码: 首先,创建客户端处理器: ```java import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import io.netty.channel.ChannelHandlerContext; import io.netty.channel.SimpleChannelInboundHandler; import java.nio.charset.Charset; import java.util.concurrent.CompletableFuture; public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> { private CompletableFuture<String> responseFuture; public NettyClientHandler(CompletableFuture<String> responseFuture) { this.responseFuture = responseFuture; } @Override public void channelActive(ChannelHandlerContext ctx) { // 当通道激活时,发送消息 String message = "Hello, Server!"; ctx.writeAndFlush(Unpooled.copiedBuffer(message, Charset.forName("UTF-8"))); } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { // 收到消息时,完成Future String response = msg.toString(Charset.forName("UTF-8")); responseFuture.complete(response); ctx.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); responseFuture.completeExceptionally(cause); ctx.close(); } } ``` 然后,创建Netty客户端启动类: ```java import io.netty.bootstrap.Bootstrap; import io.netty.channel.Channel; import io.netty.channel.ChannelFuture; 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.NioSocketChannel; import java.util.concurrent.CompletableFuture; public class NettyClient { private final String host; private final int port; public NettyClient(String host, int port) { this.host = host; this.port = port; } public CompletableFuture<String> sendMessage() throws InterruptedException { EventLoopGroup group = new NioEventLoopGroup(); CompletableFuture<String> responseFuture = new CompletableFuture<>(); 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) { ch.pipeline().addLast(new NettyClientHandler(responseFuture)); } }); // 连接服务器 ChannelFuture channelFuture = bootstrap.connect(host, port).sync(); // 等待直到连接关闭 channelFuture.channel().closeFuture().sync(); } finally { // 关闭事件循环组 group.shutdownGracefully(); } return responseFuture; } } ``` 注意:上面的NettyClient在发送消息接收到响应后,会关闭连接。但是,由于我们使用了CompletableFuture,我们可以在获取到响应后继续处理。 然而,上面的代码在发送一次消息后就会关闭连接。如果我们想要保持长连接,可以修改为不立即关闭,但这里为了简单,我们每次发送消息都建立新的连接。 在Spring Boot中,我们可以将NettyClient封装成一个Service: ```java import org.springframework.stereotype.Service; import java.util.concurrent.CompletableFuture; @Service public class NettyClientService { public String sendMessage(String host, int port, String message) throws Exception { // 注意:这里我们修改NettyClientHandler和NettyClient以支持传入消息 // 为了简化,我们这里不修改,实际应用需要调整 // 假设我们修改NettyClient,使其可以传入消息 // 这里我们暂时不实现,因为需要调整之前的代码结构 // 为了快速示例,我们假设NettyClient已经可以传入消息 // 创建客户端并发送 NettyClient client = new NettyClient(host, port); CompletableFuture<String> future = client.sendMessage(); return future.get(); // 阻塞直到获取结果 } } ``` 但是,上面的NettyClient没有支持传入任意消息,我们需要修改: 修改NettyClientHandler,使其在构造时传入要发送的消息: ```java public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> { private final CompletableFuture<String> responseFuture; private final String message; public NettyClientHandler(CompletableFuture<String> responseFuture, String message) { this.responseFuture = responseFuture; this.message = message; } @Override public void channelActive(ChannelHandlerContext ctx) { ctx.writeAndFlush(Unpooled.copiedBuffer(message, Charset.forName("UTF-8"))); } // ... 其他不变 } ``` 然后修改NettyClient的sendMessage方法,增加消息参数: ```java public CompletableFuture<String> sendMessage(String message) throws InterruptedException { // ... 其他不变 .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline().addLast(new NettyClientHandler(responseFuture, message)); } }); // ... 其他不变 } ``` 然后,在Service中: ```java public String sendMessage(String host, int port, String message) throws Exception { NettyClient client = new NettyClient(host, port); CompletableFuture<String> future = client.sendMessage(message); return future.get(); } ``` 这样,我们就可以在业务层调用这个Service来发送消息接收响应了。 注意:Netty是异步的,我们这里通过CompletableFuture.get()阻塞等待结果。在实际应用中,你可能希望使用异步回调,例如在Controller中返回一个DeferredResult或使用CompletableFuture的异步方法。 另外,我们每次发送都新建一个连接,对于频繁发送的场景,建议使用连接池或长连接。但这里为了简单,我们每次发送都新建连接。 5. 测试: 我们可以编写一个Controller来测试: ```java @RestController public class TestController { @Autowired private NettyClientService nettyClientService; @GetMapping("/send") public String send(@RequestParam String message) { try { return nettyClientService.sendMessage("localhost", 8080, message); } catch (Exception e) { e.printStackTrace(); return "Error: " + e.getMessage(); } } } ``` 注意:这里的服务器端口8080是假设的Netty服务器监听的端口。 以上就是一个简单的Spring Boot集成Netty作为客户端发送字符串接收响应的实现。 引用说明: [^1]: 本文参考了SpringBoot集成Netty实现物联网通信的背景知识。 [^2]: 在实现Netty客户端时,我们使用了类似NettyWriteResponseFilter中的异步处理思想,通过CompletableFuture来处理响应。 [^3]: 虽然引用[3]是关于服务端的,但其中关于消息处理器的设计思想可以借鉴。 §§相关问题§§ 1. 如何优化Netty客户端以支持高并发? 2. Netty客户端如何实现长连接和心跳机制? 3. 在Spring Boot中,如何优雅地关闭Netty客户端?</think>### Spring Boot集成Netty客户端实现字符串收发 下面详细介绍如何用Spring Boot构建Netty客户端,实现字符串发送和响应接收的全过程。 --- #### 一、核心步骤 1. **添加依赖** (`pom.xml`) ```xml <dependency> <groupId>io.netty</groupId> <artifactId>netty-all</artifactId> <version>4.1.86.Final</version> <!-- 使用最新稳定版 --> </dependency> ``` 2. **创建Netty客户端处理器** ```java public class ClientHandler extends SimpleChannelInboundHandler<ByteBuf> { private final CountDownLatch latch = new CountDownLatch(1); private String response; public String getResponse() throws InterruptedException { latch.await(5, TimeUnit.SECONDS); // 等待响应超时时间 return response; } @Override protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) { response = msg.toString(CharsetUtil.UTF_8); // 解码响应 latch.countDown(); ctx.close(); // 收到响应后关闭连接 } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) { cause.printStackTrace(); ctx.close(); } } ``` 3. **创建客户端启动类** ```java public class NettyClient { private final String host; private final int port; public NettyClient(String host, int port) { this.host = host; this.port = port; } public String sendMessage(String message) throws Exception { EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) { ch.pipeline() .addLast(new StringEncoder(CharsetUtil.UTF_8)) // 字符串编码器 .addLast(new ClientHandler()); // 自定义处理器 } }); ChannelFuture future = bootstrap.connect(host, port).sync(); future.channel().writeAndFlush(message); // 发送字符串 ClientHandler handler = future.channel().pipeline().get(ClientHandler.class); return handler.getResponse(); // 获取响应 } finally { group.shutdownGracefully(); } } } ``` 4. **Spring Boot服务层调用** ```java @Service public class MessageService { public String sendToServer(String message) { try { NettyClient client = new NettyClient("127.0.0.1", 8080); // 目标服务器地址 return client.sendMessage(message); } catch (Exception e) { throw new RuntimeException("Netty通信失败", e); } } } ``` 5. **REST接口调用示例** ```java @RestController @RequestMapping("/api") public class ApiController { @Autowired private MessageService messageService; @PostMapping("/send") public ResponseEntity<String> sendMessage(@RequestBody String message) { String response = messageService.sendToServer(message); return ResponseEntity.ok(response); } } ``` --- #### 二、关键配置说明 1. **编码/解码配置** - 使用`StringEncoder`自动将字符串转为`ByteBuf` - 在`channelRead0`中手动解码响应(如需自动解码可添加`StringDecoder`) 2. **同步机制** - 通过`CountDownLatch`实现请求-响应的同步等待 - 设置5秒超时防止线程阻塞 3. **连接管理** - 每次请求新建短连接(适合低频场景) - 高频场景需改用连接池或长连接(参考优化建议) --- #### 、应用场景示例 ```mermaid sequenceDiagram participant Client as SpringBoot应用 participant NettyClient participant Server as 目标服务器 Client->>NettyClient: 调用sendMessage("Hello") NettyClient->>Server: 建立TCP连接 NettyClient->>Server: 发送字符串数据 Server-->>NettyClient: 返回响应数据 NettyClient-->>Client: 返回响应字符串 ``` --- #### 四、优化建议 1. **长连接管理** ```java // 在NettyClient中维护Channel private Channel channel; public void connect() { // ...初始化连接... channel = bootstrap.connect(host, port).sync().channel(); } public String send(String msg) { channel.writeAndFlush(msg); // ...等待响应... } ``` 2. **添加心跳机制** ```java ch.pipeline() .addLast(new IdleStateHandler(0, 5, 0)) // 5秒写空闲 .addLast(new HeartbeatHandler()); // 自定义心跳包发送 ``` 3. **使用连接池** ```java GenericObjectPool<Channel> pool = new GenericObjectPool<>( new BasePooledObjectFactory<>() { @Override public Channel create() throws Exception { return bootstrap.connect(host, port).sync().channel(); } } ); ``` --- #### 五、常见问题解决 1. **乱码问题** - 确保双方使用相同字符集:`CharsetUtil.UTF_8` - 添加统一编解码器: ```java ch.pipeline() .addLast(new StringDecoder(CharsetUtil.UTF_8)) .addLast(new StringEncoder(CharsetUtil.UTF_8)) ``` 2. **响应超时** - 在`CountDownLatch.await()`设置超时时间 - 添加超时处理器: ```java ch.pipeline().addLast(new ReadTimeoutHandler(30, TimeUnit.SECONDS)); ``` 3. **线程阻塞** - 使用`CompletableFuture`实现异步调用: ```java public CompletableFuture<String> sendAsync(String message) { return CompletableFuture.supplyAsync(() -> { // ...发送逻辑... }); } ``` > **引用说明**:本方案参考了Netty官方文档的客户端实现范式[^1],并结合了Spring Boot集成网络组件的通用实践[^2]。心跳机制设计参考物联网设备通信的最佳实践[^3]。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值