I'm trying to do make simple network communication where a client sends a user input string to the server, which server then displays to the console. When I send only one string, it works fine, but as soon as I wrap my user input code and send code in a while loop, the server receives nothing.
SERVER :
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
System.out.println("Server now hosted on port " + PORT);
Socket s = serverSocket.accept();
System.out.println("A client has connected !");
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
while(true){
//RECEIVE
int data;
String inString = "";
while((data=bis.read()) != -1){
inString += (char)data;
}
System.out.println("SLAVE : " + inString);
}
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Port déjà utilisé");
}finally {
try {
serverSocket.close();
System.out.println("Server closed");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not close port " + PORT);
}
}
CLIENT :
Scanner sc = new Scanner(System.in);
Socket s = null;
try {
s = new Socket("127.0.0.1", PORT);
BufferedInputStream bis = new BufferedInputStream(s.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(s.getOutputStream());
System.out.println("Connexion established !");
while(true){ // without this while loop, it works fine
String send = "";
System.out.print(">> ");
send = sc.nextLine();
bos.write(send.getBytes());
bos.flush();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not connect");;
}
finally {
try {
s.close();
System.out.println("Closing socket");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("Could not close connection");;
}
}
System.out.println("End of client");
}
I expected the server to write any data it's reading from the socket as it's comming. But it just does nothing. I'm not quiet sure is the problem is comming from the server or the client.
while (true)loop. It serves no purpose. Once you've read -1 from the input stream, that's it, there will never be any more input.