2013-03-01 4 views
0

저는 클라이언트 서버와 자바 프로그래밍에 비교적 새로운 기능을 제공합니다. 할당을해야하고 나는이 프로그램을 사용하여 에코 클라이언트와 서버를 자바로 작성해야한다. 난 항상 여기에 내 대답을 발견하고 다시 한번 stackoverflow 리조트.IO 멀티플렉싱을 사용하는 자바 에코 서버 클라이언트

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(); 
      } 
     } 
    } 
} 

}

오류는 서버가이 때문에 종료지고 있다는 점이다 :이 클라이언트입니다

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(); 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
} 

}

:

는 서버입니다 오류 : 스레드 "main"의 예외 java.lang.ClassCastExcept ion : sun.nio.ch.Util $ 2는 java.util.ArrayList에 캐스팅 될 수 없습니다. Server_select.main (Server_select.java:40)의 에서

나머지는 괜찮은지 알고 싶습니다. 나는 이것에 관해서 내가 가지고있는 몇 가지 다른 의심을 분명히하고 싶었다. 미리 감사드립니다 :)

+2

Java 명명 규칙을 존중하십시오. 수업은 카멜 케이스로해야합니다. 그들의 이름에 밑줄이 있어서는 안됩니다. 변수는 낙타가 있습니다. –

답변

2

저는 java.nio에 익숙하지 않지만, Selector.selectedKeys()은 ArrayList가 아니라 Set를 반환합니다.