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)
You forgot "\n" in your "Hello Server".
Reader can't get the full line and throws this exception.
"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
and I recommend this too to ServerSock.
java.io.Closeable implementing object must call close ().