私はクライアント側とサーバー側のプログラムを入手しました。クライアントは、文字列を送信することによってサーバーと話し、その後、文字列を大文字に変換して返信します。問題は、クライアントがサーバーから文字列を受け取らないことです。サーバーだけが文字列で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
大文字で書かれたサーバからの応答を表示します。クライアント側から渡されたサーバ側の文字列は画面に表示されません。 – uml