1
I recently started working with sockets this week and am having difficulties. My goal is when the client sends a message the server responded with a notification. On the client side, sending to the server has no problems, but when the server sends to the client, nothing appears. Can someone help me with this problem?
CLIENT:
socket = new Socket("localhost", 8080);
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.write(message);
out.close();
System.out.println("send to server");
InputStreamReader in = new InputStreamReader(socket.getInputStream());
BufferedReader bf = new BufferedReader(in);
String string = bf.readLine();
System.out.println("server said :" + string);
SERVER:
serverSocket = new ServerSocket(8080);
while(true){
System.out.println("Accepting...");
socket = serverSocket.accept();
System.out.println("Connected...");
in = new InputStreamReader(socket.getInputStream());
bf = new BufferedReader(in);
PrintWriter out = new PrintWriter(socket.getOutputStream());
messageFromClient = bf.readLine();
System.out.println("Received: " + messageFromClient);
message = "welcome";
System.out.println("Sending...");
out.write(message);
out.flush();
System.out.println("sending done");
}
Behold in the documentation: when you close the
OutputStream
, theSocket
is also closed. So close it only at the end (or use a Try-with-Resources block which already ensures that the socket is closed, for example)– hkotsubo