Having some irritating trouble with Java sockets, my application seems to be failing at a very basic level. Part of my application requires writing filenames across a TCP connection. The receiver code is as follows:
ServerSocket serverSocket = new ServerSocket(4445);
Socket socket = serverSocket.accept();
BufferedReader reader = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String filename = reader.readLine();
While my sender code is as follows:
Socket socket = new Socket(InetAddress.getLocalHost(), 4445);
PrintWriter writer = new PrintWriter(socket.getOutputStream());
writer.write("Test.jpg");
Very, very basic stuff here, but for some reason, I’m getting a SocketException: Connection Reset when I run this? This is the full stack trace:
Exception in thread "main" java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(Unknown Source)
at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
at sun.nio.cs.StreamDecoder.read(Unknown Source)
at java.io.InputStreamReader.read(Unknown Source)
at java.io.BufferedReader.fill(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at java.io.BufferedReader.readLine(Unknown Source)
at FileReceiver.main(FileReceiver.java:11)
with the FileReceiver.java:11 line being the one where the reader.readLine() call is made. I can’t for the life of me figure out what is going wrong, similarly basic use of TCP sockets has always worked for me in the past, why is this happening now?
You need to combine what both Nick and Nikolai said:
You need to write with println (since readLine is expecting an end-of-line) and you need to flush your writer before closing it.