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

Netty 内蒂。写入处理程序外部的通道,netty,Netty,是否有一种方法可以写入事件处理程序外部的通道。我想向频道写入我在控制台中键入的字符串。可能吗 fun main() { //Bootstrapping val eventLoopGroup = NioEventLoopGroup() val serverBootstrap = ServerBootstrap() serverBootstrap.group(eventLoopGroup) serverBootstrap.channel(NioServerSo

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

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())
        }
    }
}
fun main(){
//自举
val eventLoopGroup=NioEventLoopGroup()
val serverBootstrap=serverBootstrap()
serverBootstrap.group(eventLoopGroup)
通道(NioServerSocketChannel::class.java)
serverBootstrap.localAddress(InetSocketAddress(9988))
childHandler(对象:ChannelInitializer(){
覆盖通道(通道:SocketChannel?){
通道?.pipeline()
?addLast(StringEncoder(StandardCharsets.UTF_8))
?addLast(字符串解码器(StandardCharsets.UTF_8))
?.addLast(RemoteKeyboardHandler())
}
})
val ch=serverBootstrap.bind().sync().channel()
while(true){
val input=readLine()
val future=ch.writeAndFlush(输入)
future.addListener{
println(it.isSuccess)
println(it.cause())
}
}
}

这是我的服务器代码。在处理程序中,我只是在连接时发送一个
“helloworld”
字符串。我得到
操作不支持异常
。我在上找到,因此无法写入服务器通道。也许这就是重点。那么,在这种情况下,我应该怎么做呢?

首先,如果您在这里发布您的客户机/服务器类会有所帮助的话

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

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();
当您想要添加控制台输入时,可以直接在下面执行此操作:

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);
//        }
}
导入io.netty.bootstrap.bootstrap;
导入io.netty.channel.channel;
导入io.netty.channel.ChannelInitializer;
导入io.netty.channel.EventLoopGroup;
导入io.netty.channel.epoll.epoll;
导入io.netty.channel.epoll.EpollEventLoopGroup;
导入io.netty.channel.epoll.EpollSocketChannel;
导入io.netty.channel.nio.NioEventLoopGroup;
导入io.netty.channel.socket.SocketChannel;
导入io.netty.channel.socket.nio.NioSocketChannel;
导入io.netty.handler.codec.string.StringDecoder;
导入io.netty.handler.codec.string.StringEncoder;
导入java.io.BufferedReader;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.nio.charset.StandardCharset;
公共类客户端{
私有静态最终布尔值EPOLL=EPOLL.isAvailable();
专用静态最终int端口=25112;
私有静态最终字符串HOST=“localhost”;
专用信道;
私有静态整数计数;
//相反,您可以使用一种方法来启动客户机
公共客户机(){
EventLoopGroup workerGroup=(EPOLL)?new-EpollEventLoopGroup():new-NioEventLoopGroup();
试一试{
ch=新引导()
.group(workerGroup)
.channel((EPOLL)?EpollSocketChannel.class:NioSocketChannel.class)
.handler(新的通道初始值设定项(){
@凌驾
受保护信道(SocketChannel ch){
ch.管道()
.addLast(新的StringEncoder(StandardCharsets.UTF_8))
.addLast(新的字符串解码器(StandardCharsets.UTF_8))
.addLast(新ClientMessageHandler());
}
}).connect(主机、端口).sync().channel();
//控制台输入
BufferedReader reader=新的BufferedReader(新的InputStreamReader(System.in));
字符串行=”;
而((line=reader.readLine())!=null){
if(line.startsWith(“!exit”)| line.startsWith(“!disconnect”)){
reader.close();
行=空;
ch.断开连接();
打破
}else if(line.toCharArray().length==0){
继续;
}else if(第行以(“!ping”)开头){
ch.writeAndFlush(String.valueOf(System.nanoTime());
继续;
}
ch.writeAndFlush(行);
}
//runCommandPromptReading();
}捕获(中断异常| IOE异常){
e、 printStackTrace();
}最后{
workerGroup.shutdownGracefully();
}
}
//私有void runCommandPromptReading()引发IOException{
//BufferedReader reader=新的BufferedReader(新的InputStreamReader(System.in));
//字符串行=”;
//
//而((line=reader.readLine())!=null){
//if(line.startsWith(“!exit”)| line.startsWith(“!disconnect”)){
//reader.close();
//行=空;
//ch.断开连接();
//中断;
//}else if(line.toCharArray().length==0){
//继续;
//}else if(line.startsWith(“!ping”)){
//ch.writeAndFlush(String.valueOf(System.nanoTime());
//继续;
//            }
//
//ch.writeAndFlush(行);
//        }
}

我希望这是您想要的

写入
服务器频道
不受支持,因为此
套接字
只接受新的
套接字。
您想要写入
子频道
,您在
频道初始值设定项中有一个引用
谢谢您的回复。我已经添加了代码示例。它是在Kotlin中是,但我认为它非常简单。因此,我应该存储一个通道,该通道被传递到
initChannel
方法中,对吗?这个方法可能被调用多次(对于每个新连接)。我不确定你真正想要的是什么。我只希望有一个客户端可以与服务器通信。我想为android编写一个远程键盘。因此,当你打开设备上的“键盘”时,它将连接服务器端。服务器将读取击键并将其发送到设备。这就是我的想法。我在使用吗
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);
//        }
}