2014-04-05 4 views
0

Java에서 클라이언트 - 서버 예제를 구현하는 간단한 프로그램 예를 java에서 발견했습니다.소켓 프로그래밍 - 클라이언트 - 서버 코드가 작동하지 않습니다.

클라이언트 코드 :

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

public class ClientDemo { 

    public static void main(String[] args) { 

     try { 
      Socket sock = new Socket ("127.0.0.1", 4321); 

      DataInputStream input = new DataInputStream(sock.getInputStream()); 

      boolean more_data = true; 

      while (more_data) { 

       String line = input.readLine(); 

       if(line==null) { 
        more_data = false; 
       } 
       else { 
        System.out.println(line); 
       }    
      } 
     } 
     catch (IOException e) { 
     }  
    }  
} 

서버 코드 :

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

public class SimpleServer 
{ 

public static void main(String[] args) 
{ 
    try 
{ 
     ServerSocket server = new ServerSocket (4321);    
     Socket sock = server.accept(); 
     DataInputStream inp = new DataInputStream (sock.getInputStream()); 
     PrintStream out = new PrintStream (sock.getOutputStream()); 
     output.println("server message"); 
     output.println("QUIT to Quit"); 

     boolean more_data = true; 

      while (more_data) 
    { 
       String line = inp.readLine(); 

       if(line==null) 
     { 
        more_data = false; 
       } 
       else 
       { 
        output.println("Server:" +line+"\n"); 
        if(line.trim().equals("Exit") 
     { 
         more_data = false; 
        } 
       }    
      } 
      sock.close(); 
     } 
     catch (IOException ex) 
     { 
      ex.printStackTrace(); 
     }  
    }  
} 

먼저 다음 클라이언트 서버를 실행할 때, 나는 환영 메시지를 얻을 수 있지만, 텍스트를 입력 할 때 클라이언트 콘솔이 Enter 키를 누르면 아무 일도 일어나지 않습니다.

필자는 Readline이 더 이상 사용되지 않지만 동일한 동작을하는 문서 에서처럼 BufferedInputStream의 DataInputStream을 교체하려고 시도했지만 더하기 다음 객체와 함께 scanner 객체로 변경하려고 시도했습니다.

귀하의 의견은 대단히 감사하겠습니다.

+1

것은이 답변 http://stackoverflow.com/questions/22881227/what-would-be-the-code-for-this/22881978#22881978를 참조 – drkunibar

+0

@drkunibar : 감사합니다,하지만 난하지 않았다 해당 솔루션을 제가 제공 한 코드와 연관시킵니다. 제 코드에 좀 더 구체적으로 설명해 주시겠습니까? 이 예제가 작동하려면 무엇을 변경해야합니까? – theexplorer

+1

콘솔 판독기가없고 서버에 데이터를 보내지 않는 사람이 누구입니까 – drkunibar

답변

0

이 클라이언트를 사용해보십시오. 그리고 서버를 살펴보십시오. 내가 코드를 변경 Exit하지

UPDATE

QUIT와 함께 중지하고 지금은 내 이름 ;-)

을 변경해야하는 클라이언트는 매우 간단하고 아무도 그것을 사용해서는 안 . 클라이언트는 서버가 보낼 회선의 수를 알아야합니다. 다른 스레드없이 알 수없는 행 수를 기다릴 방법이 없습니다.

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

public class ClientDemo { 

    public static void main(String[] args) { 

     try { 
      Socket sock = new Socket("127.0.0.1", 4321); 
      // Build a Buffered Reader - it is easier to read complete line 
      BufferedReader input = new BufferedReader(new InputStreamReader(sock.getInputStream())); 
      // After connecting we read the first 2 line 
      // We know that the server send 2 lines 
      System.out.println(input.readLine()); 
      System.out.println(input.readLine()); 
      // Wen must have a reader for our inputs 
      InputStreamReader consoleReader = new InputStreamReader(System.in); 
      BufferedReader in = new BufferedReader(consoleReader); 
      while (true) { 
       // read one line from the console 
       String inline = in.readLine(); 
       inline += "\n"; 
       // send the line to the server 
       sock.getOutputStream().write(inline.getBytes()); 
       sock.getOutputStream().flush(); 
       // Wait for server response - we know that we get 2 lines 
       for (int i = 0; i < 2; i++) { 
        String response = input.readLine(); 
        if (response == null || inline.equals("Exit")) { 
         break; 
        } else { 
         System.out.println(response); 
        } 

       } 
      } 
     } catch (IOException e) { 
     } 
    } 
} 
+0

감사합니다. 당신은 여전히 ​​내가 바라는 것보다 더 많이 바꿨지 만 코드에서 필요한 것을 얻고 코드의 나머지 부분을 그대로두면 작동하므로 받아 들일 것이다. – theexplorer

+0

이러한 추가 편집은 이유가있다. . – nrubin29

+0

확실합니다. 아직, 나는 어느 것이 나의 퍼즐을위한 빠진 조각인지 알고 싶었다. 귀하의 의견에 감사드립니다. – theexplorer

0

클라이언트가 콘솔에서 읽으려고 시도조차하지 않기 때문입니다. 소켓에서만 읽습니다.

+0

고마워요,하지만 당신은 명확히하실 수 있습니까? 이것이 작동하려면 무엇을 바꾸어야합니까? – theexplorer

관련 문제