Getting error “java.net.SocketException: Connectio

2019-08-16 22:38发布

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)

标签: java sockets
2条回答
做自己的国王
2楼-- · 2019-08-16 23:19

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

查看更多
倾城 Initia
3楼-- · 2019-08-16 23:37

"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 ().

查看更多
登录 后发表回答