2013-04-21 2 views
0

멀티 클라이언트와 함께 사용되는 ServerSocket은 각 클라이언트마다 별도의 스레드를 연결하여 작동하지만 문제는 연결이 정상적으로 작동하고 모든 클라이언트를 허용하지만 마지막 연결 만 제공한다는 것입니다. 그래서 문제가되지 않거나 정상입니다.멀티 클라이언트가있는 ServerSocket

서버 코드 :

ServerSocket serverSocket=null; 
    Socket client; 
     System.out.println("Establishing Connection. Please wait..."); 
    try{ 

      serverSocket =new ServerSocket(58342);    
      System.out.println("Serever Started."); 
     }catch(Exception e) 
     { 
      System.out.println(e.getMessage()); 
     } 

     while (true) { 
       try{ 
      client = serverSocket.accept(); 
        new ClientThread(client).start(); 
       }catch(Exception e) 
       { 
        String err=e.getMessage(); 
        if(err == null) 
        { 
         break; 
        }else{ 
         System.out.println(e.getMessage()); 
        } 
       } 

     } 

ClientThread

public class ClientThread extends Thread{ 

    private static Socket client; 
    private static String line=""; 
    private static DataInputStream input = null; 
    private static DataOutputStream output = null; 

    public ClientThread(Socket serv) 
    { 
     try { 
      client =serv; 
      input=new DataInputStream(client.getInputStream()); 
      output=new DataOutputStream(client.getOutputStream()); 
      System.out.println("New Client Connected to port:"+ 
        client.getPort()); 
      } catch (Exception e) { 
        System.out.println(e.getMessage()); 
      }  
    } 
} 

답변

4

ClientThread에있는 모든 변수는 static입니다 !!

이것은 ClientThread의 모든 인스턴스에서 공유되는 을 의미합니다. 그래서 그들은 new ClientThread을 만들 때마다 덮어 씁니다.

static을 제거하면 문제가 없습니다.

너는 약간 documentation을 읽을 필요가있는 것처럼 보입니다.

+0

네 말이 맞아. 같은 신분증 안에서 일한다는 걸 잊었 어. 고마워. 네가 대답하지 않으면 나는 그것을 얻지 못할 것이다. 감사하지 않기 때문에. – Alyafey

0

당신은 ClientThread의 생성자에서 I/O를 수행해야합니다.

하지 마십시오.

+0

예 편집 된 답변을 보았습니다 – Alyafey

+0

실행 방법이 완료되면 클라이언트 소켓을 닫지 않습니다. 이를 수행하는 finally 블록을 추가하십시오. – EJP

+0

나는 그것을했다. 그러나 그것은 어떤 식 으로든 도움이되지 않았다. – Alyafey