使用IO多路复用的Java echo服务器客户端



我对客户端服务器和java编程都比较陌生。有一个任务要做,我被这个程序困住了,用java写一个echo客户端和服务器。我总是在这里找到我的答案,所以我再一次求助于stackoverflow。

这是服务器:

public class Server_select {
public static void main(String[] args) throws IOException {
    int port = 4666;
    String address = "localhost";
    String channelserver = "Server Channel";
    String channelclient = "Client Channel";
    String typechannel = "Channel Type";
    ArrayList<Server_sockets> socketlist = new ArrayList<Server_sockets>();
    Iterator<Server_sockets> socketiterator = socketlist.iterator();
    ServerSocketChannel serverchannel = ServerSocketChannel.open();
    serverchannel.bind(new InetSocketAddress(address,port));
    serverchannel.configureBlocking(false);
    Selector selector = Selector.open();
    SelectionKey newconnectionkey = serverchannel.register(selector, SelectionKey.OP_ACCEPT);
    socketlist.add(new Server_sockets(serverchannel, newconnectionkey, channelserver));
    ArrayList<SelectionKey> selectedkeys = new ArrayList<SelectionKey>();
    Iterator<SelectionKey> keyiterator = selectedkeys.iterator();
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    StringBuffer message = null;
    int count;
    for(;;){
        System.out.println("Entering the infinite for loop");
        if(selector.select() == 0){
            continue;
        }
        selectedkeys = (ArrayList<SelectionKey>) selector.selectedKeys();
        while(keyiterator.hasNext()){
            SelectionKey tempkey = keyiterator.next();
            while(socketiterator.hasNext()){
                if(socketiterator.next().key.equals(tempkey)){
                    if(socketiterator.next().channeltype == channelserver){
                        SocketChannel clientchannel = socketiterator.next().serverchannel.accept();
                        SelectionKey clientkey = clientchannel.register(selector, SelectionKey.OP_READ, SelectionKey.OP_WRITE);
                        socketlist.add(new Server_sockets(clientchannel,clientkey,channelclient));
                        System.out.println("Client connection established");
                    }
                    if(socketiterator.next().channeltype == channelclient){
                        if(socketiterator.next().key.isReadable()){
                            buffer.clear();
                            message = new StringBuffer("");
                            while((count = socketiterator.next().clientchannel.read(buffer))>0){
                                buffer.flip();
                                message.append(Charset.defaultCharset().decode(buffer));
                            }
                            System.out.println("Server here " + message);
                            buffer.clear();
                            while(!(socketiterator.next().key.isWritable())){
                                buffer.wrap(message.toString().getBytes());
                                while(buffer.hasRemaining()){
                                    socketiterator.next().clientchannel.write(buffer);
                                }
                                buffer.clear();
                            }
                        }
                    }
                }
            }
        }
    }
}

}

这是客户端:

public class Client_select {

SocketChannel clientchannel;
int port = 4666;
String address = "localhost";
String message = "Hey there!";
Selector selector = null;
SelectionKey key = null;
Client_select() throws IOException{
    this.clientchannel = SocketChannel.open();
    this.clientchannel.configureBlocking(false);
    this.clientchannel.connect(new InetSocketAddress(this.address,this.port));
    this.selector = Selector.open();
    this.key = this.clientchannel.register(this.selector, SelectionKey.OP_READ, SelectionKey.OP_WRITE);
}
public void write_to_socket() throws IOException{
    ByteBuffer buffer = ByteBuffer.wrap(message.getBytes());
    while(buffer.hasRemaining()){
        this.clientchannel.write(buffer);
    }
}
public void read_from_socket() throws IOException{
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    StringBuffer message = new StringBuffer("");
    int count=0;
    while((count = this.clientchannel.read(buffer)) > 0){
        buffer.flip();
        message.append(Charset.defaultCharset().decode(buffer));
    }
    System.out.println("Read From Socket" + message);
}
public static void main(String[] args) throws Exception {
    Client_select obj = new Client_select();
    ArrayList<SelectionKey> keylist = new ArrayList<SelectionKey>();
    Iterator<SelectionKey> iterator = keylist.iterator();
    for(;;){
        System.out.println("Entering Infinite loop Client");
        if(obj.selector.select() == 0){
            continue;
        }
        keylist = (ArrayList<SelectionKey>) obj.selector.selectedKeys();
        while(iterator.hasNext()){
            if(iterator.next().isWritable()){
                obj.write_to_socket();
            }
            if(iterator.next().isReadable()){
                obj.read_from_socket();
            }
        }
    }
}

}

这个错误是服务器被终止,因为这个错误:线程"main"中的异常java.lang.ClassCastException: sun.nio.ch。Util$2不能强制转换为java.util.ArrayListServer_select.main (Server_select.java: 40)

我只是想知道剩下的还好吗?我想澄清我对这件事的其他一些疑问。提前感谢:)

我对java不是很有经验。没有,但似乎Selector.selectedKeys()返回一个Set,而不是ArrayList。

最新更新