I wrote a simple client-server program. The client connects to the server, then sends a message to the server. The server prints the message. My problem is that I don't understand why I get a SocketException: Connection reset exception when I don't call the sendMessageToServer() method. When I call the method everything works without an exception.
public class Client
{
private Socket socket;
public Client(int port) throws IOException
{
this.socket = new Socket(InetAddress.getLocalHost(), port);
// sendMessageToServer("Hello Server!\n");
}
public void sendMessageToServer(String message) throws IOException
{
try (BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));)
{
bufferedWriter.write(message);
}
catch (IOException ioe)
{
ioe.printStackTrace();
}
}
}
public class Server
{
private ServerSocket serverSocket;
ExecutorService executorService = Executors.newFixedThreadPool(3);
public Server(int port, int backlog, InetAddress inetAddress) throws IOException
{
this.serverSocket = new ServerSocket(port, backlog, inetAddress);
}
public void startListening() throws IOException
{
System.out.println("Listening...");
while (true)
{
ClientHandler clientHandler = new ClientHandler(serverSocket.accept());
System.out.println("Connected");
executorService.execute(clientHandler);
System.out.println("Waiting for another client");
}
}
}
public class ClientHandler implements Runnable
{
private Socket clientSocket;
public ClientHandler(Socket socket)
{
clientSocket = socket;
}
@Override
public void run()
{
try (
// read from client
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
)
{
// read message from client
String message = "";
String line = "";
while ((line = bufferedReader.readLine()) != null)
{
message += line;
}
System.out.println("Client message = " + message);
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
I expected that if I did not call the sendMessageToServer() method then the server would write out an empty message.