我在這裏介紹了客戶端和服務器端程序。客戶端通過發送字符串與服務器通信,服務器然後將字符串轉換爲大寫字母併發回。問題是客戶端沒有收到來自服務器的任何字符串。只有服務器打印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