2012-02-08 3 views
1

클라이언트로부터의 연결을 수신하는 프로그램이 있습니다.서버/클라이언트 통신

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

class SocketExampleServer { 

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

    int port = 5665; 
    ServerSocket ss = new ServerSocket(port); 
    System.out.println("Waiting incoming connection..."); 

    Socket s = ss.accept(); 
    DataInputStream dis = new DataInputStream(s.getInputStream()); 

    DataOutputStream out = new DataOutputStream(s.getOutputStream()); 

    String x = null; 

    try { 
     while ((x = dis.readUTF()) != null) 
     { 
     System.out.println(x); 
     out.writeUTF(x.toUpperCase()); 

     }  

    } 
    catch(IOException e) 
    { 
     System.err.println("Client closed its connection."); 
    } 
    catch(Exception e) 
    { 
     System.err.println("Unknown exception"); 
    } 

    s.close(); 
    ss.close(); 
    dis.close(); 
    out.close(); 
    System.exit(0); 
    } 


} 

것들은 이때

System.out.println(x); 
      out.writeUTF(x.toUpperCase()); 

에서만 번째 행이 실행된다는 점이다. 한 번만 줄을 바꾸면 두 번째 줄만 실행됩니다. 그 이유는 무엇입니까? 나는이 프로그램을 두 번 실행하면 그리고 한 가지 더는이 오류가 발생합니다 :

Exception in thread "main" java.net.SocketException: Unrecognized Windows Sockets error: 0: JVM_Bind 
    at java.net.PlainSocketImpl.socketBind(Native Method) 
    at java.net.PlainSocketImpl.bind(Unknown Source) 
    at java.net.ServerSocket.bind(Unknown Source) 
    at java.net.ServerSocket.<init>(Unknown Source) 
    at java.net.ServerSocket.<init>(Unknown Source) 
    at SocketExampleServer.main(SocketExampleServer.java:9) 

나는 한 시간과 포트를 업데이트해야 다음 시간 동안 실행 새에 포트 번호를 변경하면 다시 실행하려면 숫자를 입력하십시오. 나는 그 원인에 대한 이유를 얻지 못했다. 나는 소켓을 닫았고, 내 의견으로는 항구는 다음 실행을 위해 자유로울 것이다.

그 원인이 있지만, 당신의 코드에 의해 던져 체크되지 않은 예외의 가능성을 방지하기 위해 무엇 확실하지 이유는, 당신은 마지막 절에서 자원을 닫아야합니다 : 2 질문에

+0

[실제 포트를보십시오] (http://www.petri.co.il/quickly_find_local_open_ports.htm), 어떤 프로세스가 소켓을 계속 바인딩하는지 확인할 수 있습니다. –

답변

2

ServerSocket ss; 
try { 
... 
} 
finally { 
    if (ss.close() != null) { 
       ss.close(); 
    }  
} 
+0

아니요, 운영자는 결국 아무 것도 변경하지 않습니다. – uml

+0

프로그램을 정확히 실행하는 방법과 프로그램을 종료하는 방법은 무엇입니까? –

+0

먼저 (위에서) 서버를 실행 한 다음 클라이언트를 시작합니다 (여기서는 소개하지 않음). 각 파일의 끝에는 System.exit (0)이 있습니다. – uml