我的简单Java NIO客户端服务器非阻塞连接不起作用

时间:2015-10-21 07:53:49

标签: java nio

我正在尝试使用简单的客户端 - 服务器程序,最终旨在使其成为双向通信。出于某种原因,当我只是实例化客户端类以使其连接到服务器(不发送任何数据)时,它不起作用,并抛出Unable to establish loopback connection异常。当我通过while进行stdin循环阅读时,它会正常工作。我需要先建立一个连接,然后偶尔向服务器发送一条消息。我该如何解决?

客户代码:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

public class ClientCore {

    SelectionKey selkey;
    Selector sckt_manager ;
    SocketChannel sc;

    public ClientCore() {
        try {
            sc = SocketChannel.open();
            sc.configureBlocking(false);
            sc.connect(new InetSocketAddress(8888));

            // should not proceed until connect is finished
            while (!sc.finishConnect()) {
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (sc != null) {
                try {
                    sc.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    void send(String message) {
        try {
            if (!message.equalsIgnoreCase("end")) {
                System.out.println("Sending a request to the server ...");
                ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
                sc.write(buffer);
            }
        } catch (IOException e) {
        }

    }

    public static void main(String[] args) throws Exception {
        ClientCore cl = new ClientCore();
        cl.send("hello");
    }
}

服务器代码:

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.channels.WritableByteChannel;
import java.nio.channels.spi.SelectorProvider;

public class ServerCore extends Thread {

    SelectionKey selkey = null;
    Selector sckt_manager = null;

    public void run() {
        try {
            coreServer();
        } catch (Exception ej) {
            ej.printStackTrace();
        }
    }

    private void coreServer() {
        try {
            ServerSocketChannel ssc = ServerSocketChannel.open();
            try {
                ssc.socket().bind(new InetSocketAddress(8888));

                while (true) {

                    sckt_manager = SelectorProvider.provider().openSelector();
                    ssc.configureBlocking(false);
                    SocketChannel sc = ssc.accept();
                    register_server(ssc, SelectionKey.OP_ACCEPT);
                    if (sc == null) {
                    } else {

                        System.out
                                .println("Received an incoming connection from "
                                        + sc.socket().getRemoteSocketAddress());
                        printRequest(sc);
                        System.err.println("testing 1");
                        String HELLO_REPLY = "Sample Display";
                        ByteBuffer buffer = ByteBuffer.wrap(HELLO_REPLY .getBytes());
                        System.err.println("testing 2");
                        sc.write(buffer);
                        System.err.println("testing 3");
                        sc.close();
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (ssc != null) {
                    try {
                        ssc.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception E) {
            System.out.println("Ex in servCORE   " + E);
        }
    }

    private static void printRequest(SocketChannel sc) throws IOException {

        ReadableByteChannel rbc = Channels.newChannel(sc.socket()
                .getInputStream());
        WritableByteChannel wbc = Channels.newChannel(System.out);
        ByteBuffer b = ByteBuffer.allocate(1024); // read 1024 bytes
        while (rbc.read(b) != -1) {
            b.flip();
            while (b.hasRemaining()) {
                wbc.write(b);
                System.out.println();
            }
            b.clear();
        }
    }

    public void register_server(ServerSocketChannel ssc, int selectionkey_ops)
            throws Exception {
        ssc.register(sckt_manager, selectionkey_ops);
    }

    public static void main(String[] args) {
        ServerCore st = new ServerCore();
        st.coreServer();
    }
}

0 个答案:

没有答案