简体   繁体   中英

Socket Communicatin BufferedReader

I dont know much about buffer readers but mine hangs up at the line where it is supposed to read it any suggestions

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

public class Host
{

public static void main(String args[])throws Exception
{
     ServerSocket ss = new ServerSocket(5001);
     Socket s=new Socket("127.0.0.1",5001);
     s=ss.accept();

     PrintWriter writer = new PrintWriter(s.getOutputStream(), true);

     writer.write("Time");
     writer.println("time");

     BufferedReader reader = new BufferedReader(new InputStreamReader(s.getInputStream()));

     String test =reader.readLine();
     System.out.println(test);
     s.close();
     ss.close();
}

}

The peer isn't sending a line or closing the socket. Reason:

Socket s=new Socket("127.0.0.1",5001);

Here you are creating a connection to yourself.

 s=ss.accept();

Here you are throwing away that Socket and accepting a new one, which is now your end of the connection whose other end you just threw away.

String test =reader.readLine();

Here you are trying to read a line from the peer which can never arrive, as the peer is yourself and you have thrown away the Socket.

You don't need to initialize any variable when you assign it on the very next line. It should be:

Socket s = ss.accept();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM