エコークライアントサーバを作成しようとしていますが、サーバからの応答がありません。私の間違いがどこにあるのか分かりません。 私はインターネット上のいくつかの例を見てきました。あるものはInputStream/OutputStreamを使うだけですが、私はBufferedReaderとPrintWriterを使うことに決めました - これは大きな違いがありますか?エコーサーバがエコーしない
サーバー側:
public class Server {
public static void main(String[] args){
Server server = new Server();
server.runServer(Integer.parseInt(args[0]));
}
private void runServer(final int port){
ServerSocket serversckt = null;
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
try{
serversckt = new ServerSocket(port);
socket = serversckt.accept();
System.out.println("Request from client accepted!");
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
String str;
while((str = in.readLine()) != null){
System.out.println(str);
out.println(str);
out.flush();
}
}
catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
クライアント側:
public class Client{
public static void main(String[] args){
Client client = new Client();
client.runClient(Integer.parseInt(args[0]), args[1]);
}
private void runClient(final int port, final String hostname){
Socket sckt = null;
try{
sckt = new Socket(hostname, port);
BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in));
BufferedReader in = new BufferedReader(new InputStreamReader(sckt.getInputStream()));
PrintWriter out = new PrintWriter(sckt.getOutputStream(), true);
String str;
while((str = stdIn.readLine()) != null){
out.println(str);
System.out.println(in.readLine());
}
} catch(IOException e){
System.out.println(e.getMessage());
}
}
ありがとう!
サーバ内のwhile((str = in.readLine())!= null) 'はブロッキング呼び出しであるとは考えていないので、最初の読み込みで' null'になり、終了しますサーバー。たぶん、誰かが 'BufferedReader'についての知識があり、ブロックされているかもしれません。 – Tom
実際に、* echo *サーバをエコーしないechoサーバを呼び出すことはできますか? – SergeyA
@thatotherguyこれが最も重要なポイントです。コンソールから読み込み、サーバーに送信し、その "エコー"を読みます。 @OP 'System.out.println(in.readLine());'もブロックしないので、サーバがオフライン(最初のコメントを読んでいる)であるか、回答。 – Tom