2016-10-16 4 views
0

서버 (NewServer 클래스)와 클라이언트 (NewClient 클래스) 간의 통신을 설정하려고하는데 두 개의 클라이언트 통신을 수락합니다. 나는 하나의 클라이언트로 그것을하는 방법을 알고 있지만 여러 클라이언트 커넥션은 그렇지 않다.Java Multi Client 서버 소켓

  • 클라이언트 클래스에 2 개의 독자를 만들어야합니까?

  • 재귀 적으로이 작업을 수행 할 수 있습니까?

서버 클래스 :

import java.net.*; 
import java.io.*; 

public class NewServer 
{ 
    //Create Server Socket and a Client Socket for each Client. 
    static ServerSocket server; 
    static Socket client1; 
    static Socket client2; 

    //Create OutputStreams to send information to each Client. 
    static DataOutputStream client1writer; 
    static DataOutputStream client2writer; 

    static final int PORT = 9999; 

    //Main Method 
    public static void main(String[]args) 
    { 
     //Try-Catch Block for Socket Errors. 
     try 
     { 
      //Create the Server Socket as a Host. 
      server = new ServerSocket(PORT); 

      //Connect Client 1 – First run of the Client class. 
      client1 = server.accept(); 
      client1writer = new  
      DataOutputStream(client1.getOutputStream()); 

      //Connect Client 2 – Second run of the Client class. 
      client2 = server.accept(); 
      client2writer = new  
      DataOutputStream(client2.getOutputStream());    

      //Assign each Client an ID number – this is how the Client will know 
      // which individual Client it’s representing in RunTime. 
      int ID1 = 8675309; 
      int ID2 = 8675308; 

      //Tell both Clients which one they are representing. 
      client1writer.writeInt(ID1); 
      client2writer.writeInt(ID2); 

      //Close all Sockets when finished. 
      client1.close(); 
      client2.close(); 
      server.close(); 
     } 
     catch (IOException IOex) 
     { 
      System.out.println("Server Error."); 
     } 
    } 
} 

클라이언트 클래스 :

import java.net.*; 
import java.io.*; 

public class NewClient { 

    static Socket client = null;       
    static final int PORT = 9999;      
    static final String IP = "localhost";     

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

     int id1;  
     int id2;      

     try{ 
      client = new Socket(IP,PORT);  
      System.out.println("Connection successful!"); 

      reader = new DataInputStream(client.getInputStream()); 

      id1 = reader.readInt(); 
      id2 = reader.readInt();  

      System.out.println("The id of the user is " + id); 

      //Closing everything 
      client.close(); 
      reader.close(); 

     }catch(IOException error) { 
      System.err.println("Server error."); 
     } 
    } 
} 

답변

0

또한 모든 새 클라이언트 연결을 위해 일반 스레드로 알려진 별도의 스레드를 (시작하여 그것을 달성 할 수 있으며 루프로 실행되는 server.accept()으로 전화하십시오. 학습 예제로 유용하지만, 느슨해 진 상황에서 필요한 것을 달성하는 데 도움이되지 않습니다. 스레드의 트롤.

두 번째 방법은 위 해결책을 통해 더 나은 관리 제어를 제공하는 실행자 서비스 실행자 서비스를 사용하는 것입니다.