繁体   English   中英

有什么方法可以将数据作为响应从nio服务器发送到io客户端?

is there any way to send data as response from nio server to io client?

提示:本站收集StackOverFlow近2千万问答,支持中英文搜索,鼠标放在语句上弹窗显示对应的参考中文或英文, 本站还提供   中文繁体   英文版本   中英对照 版本,有任何建议请联系yoyou2525@163.com。

我可以从io客户端发送数据(仅使用套接字而不是套接字通道),但是无法从nio服务器发送数据(使用套接字通道)。 问题是什么?

通过I / O流和字节缓冲区进行读/写的方式之间有区别吗?

public class Server {

    // this is equivalent to the server socket in the non nio world
    ServerSocketChannel serverSocketChannel;

    // this is the multiplexer which multiplexes the messages received from
    // different clients
    Selector selector;

    public Server() {
        try {

            // get a selector
            selector = Selector.open();

            // get a server socket channel
            serverSocketChannel = ServerSocketChannel.open();

            // we force the socket to be Non-blocking.
            // if it is set to "true" then this socket acts as a normal
            // (blocking) server socket
            serverSocketChannel.configureBlocking(false);

            // port and ip address where the server listens for connections
            InetSocketAddress add = new InetSocketAddress(
                InetAddress.getLocalHost(), 9999);

            // bind the server socket to the ip/port
            serverSocketChannel.socket().bind(add);

            // register the serverSocketChannel (for incoming connection events)
            // to the selector.
            // The "SelectionKey.OP_ACCEPT" parameter tells the selector that
            // this serverSocketChannel registers
            // itself for incoming (acceptable) connections
            SelectionKey key = serverSocketChannel.register(selector,
                SelectionKey.OP_ACCEPT);
            System.out.println("serverSocketChannel's registered key is : "
                + key.channel().toString());

            System.out.println();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.startListening();
    }

    private void startListening() {

        System.out.println("Server is listening on: "
            + serverSocketChannel.socket().getInetAddress()
                .getHostAddress() + ":"
            + serverSocketChannel.socket().getLocalPort());

        while (true) {
            try {

                // this line blocks until some events has occurred in the
                // underlying socket
                selector.select();

                // get the selected keys set
                Set selectedKeys = selector.selectedKeys();

                Iterator iterator = selectedKeys.iterator();

                while (iterator.hasNext()) {

                    SelectionKey key = (SelectionKey) iterator.next();

                    iterator.remove();

                    // a client has asked for a new connection
                    if (key.isAcceptable()) {
                        // only ServerSocketsChannels registered for OP_ACCEPT
                        // are excepted to receive an
                        // "acceptable" key

                        System.out.println("Key ready to perform accept() : "
                            + key.channel().toString());

                        // as usual the accept returns the plain socket towards
                        // the client
                        SocketChannel client = serverSocketChannel.accept();

                        // set the client socket to be non blocking
                        client.configureBlocking(false);

                        // register the client socket with the same selector to
                        // which we have registered the
                        // serverSocketChannel
                        client.register(selector, SelectionKey.OP_READ);
                        // client.register(selector, SelectionKey.OP_WRITE);
                        continue;
                    }

                    // the client has sent something to be read by this server
                    if (key.isReadable()) {

                        System.out.println("Key ready to perform read() : "
                            + key.channel().toString());

                        // get the underlying socket
                        SocketChannel client = (SocketChannel) key.channel();
                        ByteBuffer bb = ByteBuffer.allocate(10000);

                        // read the msg sent by the client
                        client.read(bb);

                        // display the message
                        bb.flip();
                        byte[] array = new byte[bb.limit()];
                        bb.get(array);
                        System.out.println(new String(array));

                        // send the message

                        ByteBuffer bb1 = ByteBuffer.allocate(10000);

                        String s = "server data";
                        byte[] array1 = new byte[bb1.limit()];
                        array1 = s.getBytes();
                        bb1.put(array1);
                        client.write(bb1);

                    }

                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    void write() {

    }


}

public class Client {
    static String IP = "192.168.123.105"; // server IP address
    public static void main(String[] args) throws UnknownHostException,
        IOException {
        // TODO Auto-generated method stub

        String msg;
        Socket socket = new Socket(IP, 9999);

        System.out.println("client: complete making socket");
        Scanner scan = new Scanner(System.in);
        System.out.println("client: input data to send");

        while (true) {
            // read
            System.out.print(">>>");
            msg = scan.nextLine();

            OutputStream out = socket.getOutputStream();
            DataOutputStream dou = new DataOutputStream(out);
            dou.writeUTF(msg);

            // write from server

            InputStream in = socket.getInputStream();
            DataInputStream din = new DataInputStream(in);
            String remsg = din.readUTF();
            System.out.println("client: data from server" + remsg);

            if (remsg.equalsIgnoreCase("END")) {
                System.out.println("SOCKET END");
                socket.close();
                break;

            }
        }
    }
}
1 个回复

我解决了问题!

这是关于如何从客户端的输入流中读取的问题

我更改了部分客户代码

  InputStream in = socket.getInputStream();
        DataInputStream din = new DataInputStream(in);
        String remsg = din.readUTF();
        System.out.println("client: data from server" + remsg);

ByteBuffer bb1 = ByteBuffer.allocate(10000);
            byte[] array1 = new byte[bb1.limit()];
            InputStream in = socket.getInputStream();
            in.read(array1);
            String remsg=new String(array1);

并在服务器代码中添加了OP_WRITE / isWritable()这样

if (key.isReadable()) {

                    System.out.println("Key ready to perform read() : "
                            + key.channel().toString());

                    // get the underlying socket
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer bb = ByteBuffer.allocate(1024);

                    // read the msg sent by the client
                    client.read(bb);

                    // display the message
                    bb.flip();
                    byte[] array = new byte[bb.limit()];
                    bb.get(array);
                    System.out.println(new String(array));

                    client.register(selector, SelectionKey.OP_WRITE);


                    continue;
                }



 if(key.isWritable()){

                    SocketChannel client = (SocketChannel) key.channel();
                      ByteBuffer bb1 = ByteBuffer.allocate(10000);

                        String s = "server data";
                        byte[] array1 = new byte[bb1.limit()];
                        array1 = s.getBytes();
                        bb1.put(array1);
                        bb1.flip();
                        client.write(bb1);
                    }
2 如何将数据作为响应从Node.js服务器发送到AJAX客户端?

因此,我正在调用此函数以将有关HTML元素的数据作为对象发送: 服务器将比较输入对象和已经存储的对象,并响应它们是否相同: 当前,服务器获取数据并进行正确的计算,但是总是会调用客户端上的错误消息,而我不知道为什么。 此外,如果有帮助,我会在客户端控制台上不断收到此错误: ...

3 根据服务器的响应从客户端发送警报

我正在将express.js用作服务器端,并使用普通的JavaScript作为客户端。 在注册路线中,我只想在用户尚未注册时添加他/她。 如果已经注册,我想收到一条警告消息“用户已经注册”。 在注册路线中表单的提交按钮之间,将重定向到/users/add路线。 这是/users/add路 ...

5 如何将响应从servlet发送到客户端?

我正在尝试将.xml文件形式的响应从Java servlet发送到客户端。 为此,我编写了以下代码: 如何检查客户端是否收到此响应? 我需要显式发送响应还是以上代码足以将响应发送给客户端? 提前致谢 ...

7 服务器将数据发送到客户端

在我的快速项目中,我希望服务器将JSON对象发送到客户端。 客户端使用脚本来显示接收到的数据,因此我不希望直接在屏幕上看到从服务器发送的数据,我希望它首先通过javascript。 我尝试了多种发送数据的方法,但没有成功: 客户: 要么 服务器: 要么 ...

8 将数据从客户端发送到服务器

我必须在大学完成一个编程项目,并且已经决定一个需要多个客户端(树莓pis)才能与中央服务器进行交互的项目。 本质上,服务器将存储一个具有唯一向量的人员数据库。 然后,树莓派将向服务器发送一个向量,然后服务器将确定它已存储在该数据库中的向量中最接近的向量,然后它将相应地更新状态数据库。 ...

9 将数据从服务器发送到客户端

我有两个项目,一个用于服务器,另一个用于客户端。 在客户端,当我想发送数据时,我创建一个QTcpSocket成员变量,然后使用write()方法发送数据。 在服务器上,我收到了信息,但我想将信息发送回客户端。 具体来说,我正在尝试验证用户,所以我将他们在客户端登录的用户名和密码发送到服 ...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2022 STACKOOM.COM