首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >内蒂。写入处理程序外部的通道

内蒂。写入处理程序外部的通道
EN

Stack Overflow用户
提问于 2019-05-20 00:04:36
回答 2查看 578关注 0票数 1

有没有办法在事件处理程序之外写入通道。我想要向通道写入我在控制台中键入的字符串。这有可能吗?

代码语言:javascript
复制
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。我发现在上,所以我不能写到服务器通道。也许这就是重点所在。那么在这种情况下我应该怎么做呢?

EN

回答 2

Stack Overflow用户

发布于 2019-05-20 01:10:31

首先,如果你在这里发布你的客户/服务器类,这将是有帮助的。

您可以从bootstrap中获取频道对象:

代码语言:javascript
复制
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并传递字符串

代码语言:javascript
复制
channel.writeAndFlush("Example Message");

当您想要添加控制台输入时,可以直接在下面执行此操作:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2019-05-20 17:22:05

不支持写入ServerChannel,因为此socket只接受您要写入您在ChannelInitializer中引用的child Channel的新sockets.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56209607

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档