how do I send a line through the server in a loop?
Socket s1=new Socket("localhost",3001);
System.out.println("Client process");
byte b[]=new byte[150];
int n=4;
BufferedReader BR=new BufferedReader(new InputStreamReader(s1.getInputStream()));
String str=new String();
while((str=BR.readLine())!=null)
{
System.out.println();
System.out.println(str);
}
s1.close();
In the above code I'm trying to read a line from server and print that line on client machine.But the client couldn't read a line until the server is finished开发者_高级运维 writing all lines and closed.Please help me how to read a line from server at a time.
Check if the server flushes its output stream after each line.
Client code :
Socket s1=new Socket("localhost",4444);
System.out.println("Client process");
byte b[]=new byte[150];
int n=4;
BufferedReader BR= new BufferedReader(new InputStreamReader(s1.getInputStream()));
String str=new String();
while((str=BR.readLine())!=null) {
System.out.println();
System.out.println(str);
}
s1.close();
Simple server code :
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
}
catch (IOException e) {
System.err.println("Could not listen on port: 4444.");
System.exit(1);
}
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
}
catch (IOException e) {
System.err.println("Accept failed.");
System.exit(1);
}
PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String inputLine, outputLine;
// write to client
for(int i=0;i<10;i++){
out.println("hello from server" + i);
Thread.sleep(1000);
System.out.println("Server sent " + i);
}
out.close();
in.close();
clientSocket.close();
serverSocket.close();
System.err.println("Server done.. closing now..");
PS : add these into main methods , and add the throws clause with appropriate exceptions.
精彩评论