2017-02-23 8 views
1

서버와 클라이언트로 간단한 프로그램을 만들고 텍스트 문자열을 앞뒤로 전달하려고합니다. 연결에 문제가 있습니다. 소켓 받아들이 기 라인 바로 아래에 테스트 인쇄 라인이 있으며 결코 인쇄되지 않으므로 문제가 있다고 가정합니다. 그러나 더 철저한 검사를 수행하는 방법을 모르겠습니다.Java에서 소켓 연결을 수락하지 못했습니다.

나는이 프로그램을 이클립스로 작성했다.

이 서버입니다 :

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

public class HW2Q1S { 

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

    try { 
     //connection 
     ServerSocket srvr = new ServerSocket(7654); 
     Socket skt = srvr.accept(); 
     System.out.println(skt.getPort()); 

     //data xfer 
     BufferedReader sIn = new BufferedReader(new InputStreamReader(skt.getInputStream())); 
     PrintWriter sOut = new PrintWriter(skt.getOutputStream(), true); 

     //string receiving 
     int count = 1; 
     String msg = ""; 

     while((msg = sIn.readLine()) != null) { 
      while(count < 11) { 
       msg = sIn.readLine(); 
       System.out.println("Received: "+ msg); 
       String returnMsg = msg.toUpperCase(); 
       System.out.println("Capped: "+ returnMsg); 
       sOut.write(returnMsg); 
       count++; 
      } 
     } //end of read from client in while loop 
     if (count == 10) { 
      System.out.println("Max reached."); 
     } 
     srvr.close(); 
     return; 
    } 

    catch(Exception e) { 
     System.out.println("Error caught: " + e); 
    } 

} // end of main 
} // end of class 

그리고 이것은 클라이언트입니다 :

import java.util.Random; 
import java.io.*; 
import java.net.*; 

public class HW2Q1C { 

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

    String capped = ""; 
    String temp = ""; 

    try { 
     //make the connection 
     Socket skt = new Socket("localhost", 7654); 
     BufferedReader cIn = new BufferedReader(new InputStreamReader(skt.getInputStream())); 
     PrintWriter cOut = new PrintWriter(skt.getOutputStream(), true); 

     //send 11 strings 
     for (int i = 0; i < 11; i++) { 
      temp = Stringer(); 
      cOut.write(temp); 
      System.out.println("Sending: " + temp); 

     } 

     //receive server strings 
     while(cIn.readLine() != null) { 
     capped = cIn.readLine(); 
     System.out.println("From server: "+ capped); 
     } 

     skt.close(); 
    } // end of connection try block 

    catch(Exception e) { 
     System.out.print("Whoops! It didn't work!\n"); 
    } 

} //end of main 

static String Stringer() { 
    String msg, alpha; 
    msg = ""; 
    alpha = "abcdefghijklmnopqrstuvwxyz"; 
    Random rnd = new Random(); 
    for (int i = 0; i < 10; i++) { 
     msg += alpha.charAt(rnd.nextInt(25)); 
    } 
    return msg; 
} 
} //end of class 

감사합니다!

+1

예외가 발생했을 것으로 추측합니다. 스택 추적은 무엇입니까? 디버깅 해봤습니까? – Altoyyr

+0

그것이 내가 생각한 것이지만 콘솔에는 아무것도 없다. 그것은 완전히 비어 있습니다. – TurtleOrRodeo

+1

난 방금 당신의 프로그램을 실행하고 내가 볼 수있는 한 연결 자체는 괜찮습니다. srvr.accept()는 클라이언트가 연결될 때까지 기다립니다 (제대로 수행함). 이것은 도움이 될 것입니다. http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html – Altoyyr

답변

2

문제가 있다고 생각합니다.
write 대신 println을 사용해야합니다. 문제는 쓰기가 실제 행 string + \n을 보내지 않으므로 서버가 행을 읽을 수 없다는 것입니다.
나는 쉽게 테스트하고 이해할 수 있도록하기 위해 예를 약간 수정, 그러나 이것은 나를 위해 작동 :

서버 :

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

public class Server { 
    public static void main(String[] args) throws Exception { 
     try { 
      //connection 
      ServerSocket srvr = new ServerSocket(7654); 
      Socket skt = srvr.accept(); 
      System.out.println(skt.getPort()); 

      BufferedReader in = new BufferedReader(new InputStreamReader(skt.getInputStream())); 

      String msg = ""; 
      while ((msg = in.readLine()) != null) { 
       System.out.println("Received: " + msg); 
      } //end of read from client in while loop 
      srvr.close(); 
     } catch (Exception e) { 
      System.out.println("Error caught: " + e); 
     } 

    } // end of main 
} // end of class 

클라이언트 :

import java.util.Random; 
import java.io.*; 
import java.net.*; 

public class Client { 

    public static void main(String[] args) throws IOException { 
     try { 
      Socket socket = new Socket("localhost", 7654); 
      PrintWriter out = new PrintWriter(socket.getOutputStream(), true); 

      for (int i = 0; i < 11; i++) { 
       out.println(Stringer()); //<-- println instead of write 
      } 
      socket.close(); 
     } // end of connection try block 
     catch(Exception e) { 
      System.out.print(e.toString()); 
     } 

    } //end of main 

    static String Stringer() { 
     String msg, alpha; 
     msg = ""; 
     alpha = "abcdefghijklmnopqrstuvwxyz"; 
     Random rnd = new Random(); 
     for (int i = 0; i < 10; i++) { 
      msg += alpha.charAt(rnd.nextInt(25)); 
     } 
     return msg; 
    } 
} //end of class 

SERVEROUTPUT :

수신 : scnhnmaiqh
수신 : kuofypeefy
을받은 : : tuussdmqqr
는 수신받은 vghsinefdi
: 수신 ysomirnfit
:
받은 lbhqjfbdio : 수신 qhcguladyg
: 수신 wihrogklfi
을 : 수신 fmpdcbtxqb
:
받은 tipikgfvsx

을 yujtuefqft
+0

그게 고마워요. – TurtleOrRodeo