I'm trying to write a code for a simple chat app with java sockets. This is the code of the server
public class MyServerSocket implements Runnable {
List<Connexion> connexions = new ArrayList<>();
final int PORT=7878;
@Override
public void run() {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(PORT);
System.out.println ("I'm waiting for clients to connect");
Socket socket = null;
while (true) {
socket = serverSocket.accept();
System.out.println("A client is connected, IP : " + socket.getInetAddress());
Connexion connexion = new Connexion(socket);
connexions.add(connexion);
Thread process_connexion = new Thread(connexion);
process_connexion.start();
}
} catch (IOException e) {
throw new RuntimeException(e);
}
// serverSocket.close();
}
public void broadcast(String message) {
this.connexions.forEach(connexion -> {
if (connexion != null) {
connexion.sendMessage(message);
}
});
}
class Connexion implements Runnable{
private Socket socket = null;
private String nickName;
private BufferedReader in;
private PrintWriter out;
public Connexion (Socket s) {
this.socket = s;
}
public void run() {
try {
InputStream IS = socket.getInputStream();
InputStreamReader ISR = new InputStreamReader(IS);
in = new BufferedReader(ISR);
OutputStream OS = socket.getOutputStream();
out = new PrintWriter(OS, true);
// here is the problem
// when i replace println with print method
// the code won't work any more
out.println("Hi Client");
out.println("Enter your name : ");
String requete = in.readLine();
this.nickName = requete;
out.println("You are connected, you can type what you want!");
while ((requete = in.readLine()) != null) {
broadcast(this.nickName + " : " + requete);
System.out.println(requete);
}
out.println("Connection lost!");
in.close();
out.close();
socket.close();
} catch (Exception e) {
try {
socket.close();
} catch (IOException ex) {
throw new RuntimeException(ex);
}
}
}
public void sendMessage(String message) {
out.println(message);
}
}
}
The code is working, but when i replace the mentioned println method (above in the code), or any println method related to output stream of socket, to print problems occur.
When i use println, the output of the server looks like output of the server and client output looks like client output But when i use print instead, the output of the server looks like output of the server and client output looks like client output I use the same code of client in the two exemples. My question is why the print method doesn't work like println does.
From the Javadoc:
Since you're not calling
printlnanymore, there will be no automatic flushing. Callflush()manually to send the data.