我想制作一个简单的 Netty 服务器,并且我有基本的服务器/客户端代码,但我有一个问题。如何从客户端主类外部写入服务器?
代码如下:
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public final class ChatClient {
static final String HOST = System.getProperty("host", "127.0.0.1");
static final int PORT = Integer.parseInt(System.getProperty("port", "8992"));
public static void main(String[] args) throws Exception {
EventLoopGroup group = new NioEventLoopGroup();
try {
Bootstrap b = new Bootstrap();
b.group(group)
.channel(NioSocketChannel.class)
.handler(new ChatClientInitializer());
Channel ch = b.connect(HOST, PORT).sync().channel();
ChannelFuture lastWriteFuture = null;
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
for (;;) {
String line = in.readLine();
if (line == null) {
break;
}
// WRITE TO SERVER, HOW DO I CALL THIS OUTSIDE FROM THIS CLASS TO WRITE TO THE SERVER?
lastWriteFuture = ch.writeAndFlush(line + "\r\n");
}
if (lastWriteFuture != null) {
lastWriteFuture.sync();
}
} finally {
group.shutdownGracefully();
}
}
}
正如评论中所述,我想从此类外部向服务器发送消息。我怎样才能做到这一点?
最诚挚的问候, 亚历克斯
最佳答案
您可以通过 getter 公开 Channel 并使用它,从而从外部访问 Channel。 Channel 是线程安全的,因此可以在任何线程中使用。
关于java - Netty IO 从类外部写入服务器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28261071/