净额。写入处理程序外部的频道

时间:2019-05-19 16:04:36

标签: netty

是否有一种方法可以在事件处理程序之外写入通道。我想将在控制台中键入的字符串写入通道。有可能吗?

fun main() {
    //Bootstrapping
    val eventLoopGroup = NioEventLoopGroup()
    val serverBootstrap = ServerBootstrap()
    serverBootstrap.group(eventLoopGroup)
    serverBootstrap.channel(NioServerSocketChannel::class.java)
    serverBootstrap.localAddress(InetSocketAddress(9988))
    serverBootstrap.childHandler(object : ChannelInitializer<SocketChannel>() {
        override fun initChannel(channel: SocketChannel?) {
            channel?.pipeline()
                ?.addLast(StringEncoder(StandardCharsets.UTF_8))
                ?.addLast(StringDecoder(StandardCharsets.UTF_8))
                ?.addLast(RemoteKeyboardHandler())
        }
    })

    val ch = serverBootstrap.bind().sync().channel()
    while (true) {
        val input = readLine()
        val future = ch.writeAndFlush(input)
        future.addListener {
            println(it.isSuccess)
            println(it.cause())
        }
    }
}

这是我的服务器代码。在处理程序中,我只是在连接时发送一个"Hello world"字符串。我得到OperationNotSupportedException。我在SO上发现无法写入服务器通道。也许这就是重点。那么在这种情况下我该怎么办?

2 个答案:

答案 0 :(得分:1)

首先,如果您在此处发布客户端/服务器类,这对您有帮助。

您可以从引导程序获取通道对象:

Channel channel = new Bootstrap()
                    .group(workerGroup)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline()
                                    .addLast(new StringEncoder())
                                    .addLast(new StringDecoder())
                                    .addLast(new YourChannelHandler();
                        }
                    }).connect(YourIp, YourPort).sync().channel();

.channel()返回一个通道,您可以在其中使用writeAndFlush并传递一个字符串

channel.writeAndFlush("Example Message");

要添加控制台输入时,可以直接在下面进行操作:

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.epoll.Epoll;
import io.netty.channel.epoll.EpollEventLoopGroup;
import io.netty.channel.epoll.EpollSocketChannel;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

public class Client {

    private static final boolean EPOLL = Epoll.isAvailable();
    private static final int PORT = 25112;
    private static final String HOST = "localhost";

    private Channel ch;

    private static Integer count;


    // instead you can use a method to start the client
    public Client() {
        EventLoopGroup workerGroup = (EPOLL) ? new EpollEventLoopGroup() : new NioEventLoopGroup();

        try {
            ch = new Bootstrap()
                    .group(workerGroup)
                    .channel((EPOLL) ? EpollSocketChannel.class : NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {

                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ch.pipeline()
                                    .addLast(new StringEncoder(StandardCharsets.UTF_8))
                                    .addLast(new StringDecoder(StandardCharsets.UTF_8))
                                    .addLast(new ClientMessageHandler());
                        }
                    }).connect(HOST, PORT).sync().channel();


            // console input
            BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
            String line = "";

            while ((line = reader.readLine()) != null) {
                if (line.startsWith("!exit") || line.startsWith("!disconnect")) {
                    reader.close();
                    line = null;
                    ch.disconnect();
                    break;
                } else if (line.toCharArray().length == 0) {
                    continue;
                } else if (line.startsWith("!ping")) {
                    ch.writeAndFlush(String.valueOf(System.nanoTime()));
                    continue;
                }

                ch.writeAndFlush(line);
            }

            //runCommandPromptReading();
        } catch (InterruptedException | IOException e) {
            e.printStackTrace();
        } finally {
            workerGroup.shutdownGracefully();
        }
    }

//    private void runCommandPromptReading() throws IOException {
//        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
//        String line = "";
//
//        while ((line = reader.readLine()) != null) {
//            if (line.startsWith("!exit") || line.startsWith("!disconnect")) {
//                reader.close();
//                line = null;
//                ch.disconnect();
//                break;
//            } else if (line.toCharArray().length == 0) {
//                continue;
//            } else if (line.startsWith("!ping")) {
//                ch.writeAndFlush(String.valueOf(System.nanoTime()));
//                continue;
//            }
//
//            ch.writeAndFlush(line);
//        }
}

我希望这就是你想要的

答案 1 :(得分:0)

不支持写入ServerChannel,因为此socket仅接受新的sockets.。您想写入child Channel,您在{{ 1}}。