java - Netty IO 从类外部写入服务器

标签 java class client netty server

我想制作一个简单的 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/

相关文章:

java - 如何使用 ListIterator 编辑列表内容

java - 在 2d 列表中,哪条路是行,哪条路是列?

Swift - 类型没有成员

C++试图通过getline函数为函数调用获取用户输入值

Java 客户端/服务器应用程序不会 readLine()

Javascript WebSocket 未连接

java - PHP 和 ESB(带 Mule)(ESB : Enterprise Service Bus)

java - 最长递增序列二维矩阵递归

python - "subtracting"字符串,python 中的类

java - Jmx 客户端抛出 InstanceNotFoundException