2012-03-03 105 views
1

我在这里介绍了客户端和服务器端程序。客户端通过发送字符串与服务器通信,服务器然后将字符串转换为大写字母并发回。问题是客户端没有收到来自服务器的任何字符串。只有服务器打印2个字符串,然后服务器抛出IOException。我想这是因为客户端关闭了连接。但为什么客户端没有收到来自服务器的任何消息?如何解决这个问题? 感谢客户端和服务器之间的通信出现了一些故障

Client: 
package solutions; 

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

class SocketExampleClient { 

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

    String host = "localhost"; // hostname of server 
    int port = 5678;   // port of server 
    Socket s = new Socket(host, port); 
    DataOutputStream dos = new DataOutputStream(s.getOutputStream()); 
    DataInputStream dis = new DataInputStream(s.getInputStream()); 

    dos.writeUTF("Hello World!"); 
    System.out.println(dis.readUTF()); 

    dos.writeUTF("Happy new year!"); 
    System.out.println(dis.readUTF()); 

    dos.writeUTF("What's the problem?!"); 
    System.out.println(dis.readUTF()); 

    } 
} 

服务器:

package solutions; 

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

class SocketExampleServer { 

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

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

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

    String x = null; 

    try { 
     while ((x = dis.readUTF()) != null) { 

     System.out.println(x); 

     dos.writeUTF(x.toUpperCase()); 
     } 
    } 
    catch(IOException e) { 
     System.err.println("Client closed its connection."); 
    } 
    } 
} 

输出:

Waiting incoming connection... 
Hello World! 
Happy new year! 
What's the problem?! 
Client closed its connection. 

回答

2

你的主程序退出它有机会从服务器读取响应之前运行一个单独的线程。如果你添加下面的代码,它会正常工作。 :)更新 - 我刚刚意识到你的代码在我的电脑上工作正常 - 并且它按照预期输出字符串。 DataInputStream.readUTF()正确阻塞并接收响应。你仍然有问题吗?

Thread t = new Thread(){ 
public void run() 
{ 
    for(;;) 
    { 
     String s = null; 
    try 
     { 
     s = dis.readUTF(); 
    } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
     } 
     while(s!=null) 
     { 
      System.out.println("Output: " + s); 
     try 
     { 
     s = dis.readUTF(); 
    } 
     catch (IOException e) 
     { 
     e.printStackTrace(); 
    } 
    }}}}; 
    t.start(); 
+0

但是为什么在读取服务器响应之前退出?客户端写入然后读取,然后写入 - 读取等等。它是按顺序的。 – uml 2012-03-03 14:29:38

+0

它以大写字母打印服务器的响应。尽管在服务器端,客户端传入的字符串不会被打印在屏幕上。 – uml 2012-03-03 17:20:19

0

凡在您的客户端的代码,你等待服务器的输入?当你的客户完成发送它终止的消息并且套接字关闭时,

你应该听到服务器的解答或look at this example

+0

客户端发送字符串下面的下一行应该从服务器读取字符串。 – uml 2012-03-03 13:55:45

+0

哦对不起,我只是不习惯看到它这样。我明白你试着做一些非常快的事情来检查它,但你应该使用上面例子中描述的方法。 – giorashc 2012-03-03 15:52:50