【问题标题】:Netty IO write to server from outside the classNetty IO 从类外写入服务器
【发布时间】:2015-03-31 09:57:50
【问题描述】:

我想做一个简单的 Netty 服务器,我有基本的服务器/客户端代码,但是我有一个问题。如何从 Client Main 类外部写入服务器?

代码如下:

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();
        }
    }
}

如 cmets 中所述,我想从此类外部向服务器发送消息。我该怎么做?

最好的问候, 亚历克斯

【问题讨论】:

    标签: java class client netty server


    【解决方案1】:

    您可以通过 getter 公开 Channel 并使用它,从而使 Channel 可以从外部访问。 Channel 是线程安全的,因此可以在任何线程中使用。

    【讨论】:

    • 你能举个例子吗?我知道 getter 和 setter 是什么,但我真的无法想象如何做到这一点:( 谢谢
    猜你喜欢
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 2013-01-27
    • 2012-07-14
    • 1970-01-01
    相关资源
    最近更新 更多