Netty IO从类外部写入服务器

时间:2015-02-01 08:59:57

标签: java class client netty server

我想创建一个简单的Netty Server,我有基本的服务器/客户端代码,但是我遇到了问题。如何从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();
        }
    }
}

如评论中所述,我想从此课程外部向服务器发送消息。我怎么能这样做?

最诚挚的问候, 亚历

1 个答案:

答案 0 :(得分:0)

您可以通过吸气剂将通道从外部访问并使用它。 Channel是线程安全的,因此可以在任何线程中使用。