2017-02-01 3 views
0

나는 서버 - 클라이언트 통신에 대해 배우고, 간단한 커뮤니케이터를 만들었지 만 작동하지만 서버에 하나의 메시지 만 보낼 수 있습니다. 나는 클라이언트에게서 더 많은 메시지를 보내고받을 수있는 가능성을 만드는 방법을 모른다. 나는 많은 옵션을 시도했지만 아무 것도 작동하지 않습니다.java - 클라이언트 - 서버 클라이언트에서 여러 메시지

내 코드는 다음과 같습니다. 클라이언트 : import java.io. ; import java.net.;

public class Klient 
    { 
     public static final int PORT=50007; 
     public static final String HOST = "127.0.0.1"; 

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

     Socket sock;                  
     sock=new Socket(HOST,PORT);              
     System.out.println("communication works: "+sock);        


     BufferedReader klaw;                
     klaw=new BufferedReader(new InputStreamReader(System.in));      
     PrintWriter outp;                 
     outp=new PrintWriter(sock.getOutputStream());          


     System.out.print("<Sending:> ");             
     String str=klaw.readLine();              
     outp.println(str);                
     outp.flush();                  


     klaw.close();                  
     outp.close();                  
     sock.close();                  
    }                     
} 

및 서버 :

// infinite loop 
while (true) { 

    // ..receive or send commands here.. 

    if (command.equals("exit") { 
    // exit from loop 
    } 

} 

은 또한 예외 처리를 추가 : 예

을 종료하기위한 코드 및 특수 명령 메인 루프를 추가 할 필요가

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

public class Serwer 
{ 
    public static final int PORT=50007; 

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

     ServerSocket serv;              
     serv=new ServerSocket(PORT);           


     System.out.println("listen for: "+serv);        
     Socket sock;               
     sock=serv.accept();              
     System.out.println("communication: "+sock);       


     BufferedReader inp;              
     inp=new BufferedReader(new InputStreamReader(sock.getInputStream())); 

     String str;                
     str=inp.readLine();              
     System.out.println("<it comes:> " + str);        


     inp.close();               
     sock.close();               
     serv.close();               
    }                   
} 

답변

0

(try-catch-finally) 또는 앱이 매우 약해집니다.

0

TCP 소켓은 데이터를 스트림으로 보냅니다. TCP는 "메시지"또는 "블록"의 데이터 전송을 지원하지 않습니다. 코드에서 수행중인 작업은 스트림을 보내고받는 것입니다.

TCP를 사용하여 "메시지"를 보내려면 TCP 위에 응용 프로그램 프로토콜을 정의해야합니다. 이 프로토콜은 "메시지"를 보낼 수 있어야합니다. (이 부분을 이해하지 못한다면 프로토콜 레이어, 7 레이어 OSI 모델, 5 레이어 TCP/IP 제품군에 대해 읽어야합니다.

메시지 종결 문자를 정의하는 방법이 있습니다. 스트림은 다음과 같이 보입니다.

<message><termination-character><message><termination-character> 

종료 문자는 메시지 문자 세트의 문자이거나 외부의 문자입니다. 후자의 경우 메시지의 종료 문자가 이스케이프 시퀀스로 바뀌어야합니다.

우리는 '\ n'을 종료 문자로 사용하고 '\ n'이 메시지 charset에 없다고 가정합니다.

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

    public class Klient 
    { 
    public static final int PORT=50007; 
    public static final String HOST = "127.0.0.1"; 
    public static final char TERMINATIONCHAR = '\n'; 

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

     Socket sock;                  
     sock=new Socket(HOST,PORT);              
     System.out.println("communication works: "+sock);        


     BufferedReader klaw;                
     klaw=new BufferedReader(new InputStreamReader(System.in));      
     PrintWriter outp;                 
     outp=new PrintWriter(sock.getOutputStream());          

     //define the loop 
     while(true){ 
      System.out.print("<Sending:> ");             
      String str=klaw.readLine(); 
      outp.print(str+TERMINATIONCHAR);                
      outp.flush(); 
     } 

     /* uncomment if the loop can be exited 
     klaw.close();                  
     outp.close();                  
     sock.close();*/ 
    }                     
} 

을하고 서버는 다음과 같이한다 : 클라이언트는 다음과 같이한다

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

public class Server 
{ 
    public static final int PORT=50007; 
    public static final char TERMINATIONCHAR = '\n'; 

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

     ServerSocket serv;              
     serv=new ServerSocket(PORT);           


     System.out.println("listen for: "+serv);        
     Socket sock;               
     sock=serv.accept();              
     System.out.println("communication: "+sock);       


     BufferedReader inp;              
     inp=new BufferedReader(new InputStreamReader(sock.getInputStream())); 

     //define the loop 
     while(true){ 
      String str;                
      str=inp.readLine();            
      System.out.println("<it comes:> " + str); 
     } 

     /* uncomment if the loop can be exited 
     inp.close();               
     sock.close();               
     serv.close();*/                 
    }                   
}