java netty 发送消息
时间: 2024-01-12 10:23:03 浏览: 87
java netty通信
以下是使用Java 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;
public class NettyClient {
public static void main(String[] args) throws Exception {
String host = "localhost";
int port = 8080;
EventLoopGroup workerGroup = new NioEventLoopGroup();
try {
Bootstrap bootstrap = new Bootstrap();
bootstrap.group(workerGroup)
.channel(NioSocketChannel.class)
.option(ChannelOption.SO_KEEPALIVE, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ch.pipeline().addLast(new NettyClientHandler());
}
});
ChannelFuture future = bootstrap.connect(host, port).sync();
Channel channel = future.channel();
// 发送消息
String message = "Hello, Netty!";
channel.writeAndFlush(message);
// 关闭连接
channel.closeFuture().sync();
} finally {
workerGroup.shutdownGracefully();
}
}
}
```
请注意,上述代码中的`NettyClientHandler`是一个自定义的处理器,用于处理接收到的消息。你可以根据自己的需求来实现该处理器。
阅读全文