2014-02-17 53 views
0

我试图用Java创建一个非常简单的程序Socket/ServerSocket。下面列出了我的两个类,它们都在同一台机器上运行。问题是,连接似乎建立得很好,但是当我试图从客户端向服务器写入套接字时,似乎没有任何事情发生。服务器永远不会从in.readLine()返回,并且程序停止。我无法弄清楚为什么会发生这种情况。Java中的基本Socket编程

这里是我的课:

TheServer.java:

public class TheServer { 
    public static void main(String[] args) { 
    BufferedReader in = null; 
    PrintWriter out = null; 

    try { 
     ServerSocket serv = new ServerSocket(2255); 
     Socket sock = serv.accept(); 
     in = new BufferedReader(
       new InputStreamReader(sock.getInputStream())); 
     out = new PrintWriter(sock.getOutputStream()); 

    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    System.out.println("Connection established by Server"); 

    try { 
     String line; 
     while ((line = in.readLine()) != "Bye") { 
      System.out.println(line + "Received"); 
      out.println(line.toUpperCase()); 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    } 
} 

TheClient.java:

public class theClient { 
    public static void main(String[] args) { 
    BufferedReader in = null; 
    PrintWriter out = null; 

    try { 
     Socket sock = new Socket("localhost", 2255); 
     in = new BufferedReader(
       new InputStreamReader(sock.getInputStream())); 
     out = new PrintWriter(sock.getOutputStream()); 
    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    System.out.println("Connection established by Client"); 

    try { 
     while (true) { 
      BufferedReader read = new BufferedReader(new InputStreamReader(
        System.in)); 
      String line = read.readLine(); 
      out.println(line.trim()); 
      System.out.println(in.readLine().trim()); 

      if (line == "Bye") 
       break; 
     } 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    } 
} 
+0

你是否通过了行尾(\ n)在数据中?我想我也曾经遇到过这种情况。由于您正在阅读每一面的线条,因此您需要发送EOL。 – mikemil

+1

'println()'将EOL附加到它发送的每一行 – ewok

+0

我运行修复程序,它看起来像是有效的。看起来终止的情况并不是如此。 !=“Bye”可能需要 - > while(!(line = in.readLine())。equalsIgnoreCase(“Bye”)){ – mikemil

回答

3

为PrintWriter对象,在每个写尝试,

obj.flush();