我在这里介绍了客户端和服务器端程序。客户端通过发送字符串与服务器通信,服务器然后将字符串转换为大写字母并发回。问题是客户端没有收到来自服务器的任何字符串。只有服务器打印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.
但是为什么在读取服务器响应之前退出?客户端写入然后读取,然后写入 - 读取等等。它是按顺序的。 – uml 2012-03-03 14:29:38
它以大写字母打印服务器的响应。尽管在服务器端,客户端传入的字符串不会被打印在屏幕上。 – uml 2012-03-03 17:20:19