1

I am learning Socket Programming in Java. I am getting java.net.SocketException: Connection reset.

Client Side Code

 package com.socket; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.Socket; public class ClientSock { public static void main(String[] args) throws Exception { Socket skt = new Socket("localhost", 8888); String str = "Hello Server"; OutputStreamWriter osw = new OutputStreamWriter(skt.getOutputStream()); PrintWriter out = new PrintWriter(osw); osw.write(str); osw.flush(); } } //Server Side Code: package com.socket; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class ServerSock { public static void main(String[] args) throws Exception { System.out.println("Server is Started"); ServerSocket ss = new ServerSocket(8888); Socket s = ss.accept(); BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream())); String str = br.readLine(); System.out.println("Client Says : " + str); } } 

Here is my console after run client code, I am getting Exception Connection reset, where I am doing wrong?

 Server is Started Exception in thread "main" java.net.SocketException: Connection reset at java.net.SocketInputStream.read(Unknown Source) 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 com.socket.ServerSock.main(ServerSock.java:19) 
2

2 Answers 2

3

"Exception in thread "main" java.net.SocketException: Connection reset" error occurs when the opponent is forcibly terminated without calling close().

Add this line to ClientSock

skt.close(); 

and I recommend this too to ServerSock.

ss.close(); 

java.io.Closeable implementing object must call close ().

2
  • 1
    skt.close will remove the exception but not the root cause of the exception. There can be multiple casues of SocektExceptionCommentedApr 14, 2017 at 7:49
  • Yes, exception gone!!! I close both Socket and ServerSocket. Well Thanks @Seongmin Gwon and Vineet Kasat.CommentedApr 14, 2017 at 11:22
0

You forgot "\n" in your "Hello Server".
Reader can't get the full line and throws this exception.

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.