简体   繁体   中英

Sending Message from NIO Server

The code below successfully creates a server and accepts an incoming client.

package socket;

import java.nio.*;
import java.nio.channels.*;
import java.net.*;
import java.util.*;
import java.io.IOException;

public class NonBlockingServer {

    public static void main(String[] args) throws InterruptedException, IOException {

        // Create a new Thread
        Server s = new Server();
        new Thread(s).start();

        // Give 10 seconds for client to connect
        Thread.sleep(10000);

// This Doesn't work?

        s.Write("Hello, Client!");

        System.out.println("Done");
    }
}

//A class which implements Runnable Interface
class Server implements Runnable  {

    SocketChannel AcceptedClient;
    ServerSocketChannel serverChannel;
    Selector selector;

    void Write(String s) throws IOException {
        ByteBuffer buffer = ByteBuffer.allocate(s.length());
        buffer.put(s.getBytes());

        int numWrite = -1;
        numWrite = AcceptedClient.write(buffer);

        while (buffer.hasRemaining())
        {
            numWrite += AcceptedClient.write(buffer);
        }

        System.out.println(numWrite);
    }

    @Override
    public void run()
    {

        int port = 4041;

        System.out.println("Listening for connections on port " + port);

        try {
            // Bind the port
            serverChannel = ServerSocketChannel.open();
            ServerSocket ss = serverChannel.socket();
            InetSocketAddress address = new InetSocketAddress(port);
            ss.bind(address);

            // Non-blocking Server
            serverChannel.configureBlocking(false);

            // Register with Selector
            selector = Selector.open();
            serverChannel.register(selector, SelectionKey.OP_ACCEPT);

        } catch (IOException ex) {
            ex.printStackTrace();
            return;
        }

        while (true) {

            try {

                // Blocks until a 'socket' is ready registered with selector is ready.
                selector.select();

            } catch (IOException ex) {
                ex.printStackTrace();
                break;
            }

            Set<SelectionKey> readyKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = readyKeys.iterator();

            while (iterator.hasNext()) {

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

                try {

                    if (key.isAcceptable()) {

                        ServerSocketChannel server = (ServerSocketChannel) key.channel();
                        SocketChannel client = server.accept();
                        System.out.println("Accepted connection from " + client);
                        client.configureBlocking(false);

                        // Client accepted by server can read.
                        SelectionKey key2 = client.register(selector, SelectionKey.OP_READ);

                        AcceptedClient = (SocketChannel) key2.channel();

                    }

                } catch (IOException ex) {
                    key.cancel();
                    try {
                        key.channel().close();
                    } catch (IOException cex) {
                    }
                }
            }
        }
    }
} 

But when I try to send a message to client after it has been connected to server, it doesn't work ie the message is not received by client.

What's the correct way to send a message from server to a specific client?

I have looked over the Internet and didn't find any examples in which server sends a message to client.

You need to flip() the buffer before the write() , and if you're going to keep it you need to compact() it afterwards.

NB Closing the channel cancels the key.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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