0

I have written a simple java code using sockets to get input from a local txt file and save it by creating another txt file in my storage elsewhere. I am using my client program to send the data and the server program to receive the data and save it. I run my server program before my client program and after running that client program, I get my output in the console that the connection has been established (I have written that in my code while trying to debug it) but, after the connection established message, I am getting The following error in my Server program:

Exception in thread "main" java.net.SocketException: Connection reset
at java.base/sun.nio.ch.NioSocketImpl.implRead(NioSocketImpl.java:323)
at java.base/sun.nio.ch.NioSocketImpl.read(NioSocketImpl.java:350)
at java.base/sun.nio.ch.NioSocketImpl$1.read(NioSocketImpl.java:803)
at java.base/java.net.Socket$SocketInputStream.read(Socket.java:982)
at Assignment_2.DA_FileServer.main(DA_FileServer.java:16)

Following is my Client program code:


    public class DA_FileClient {
        public static void main(String args[]) throws Exception{
            Socket cs = new Socket("localhost",5050);

            byte[] b = new byte[12345];
            FileInputStream fis = new FileInputStream("D:\\Coding Practice\\Source.txt");
            fis.read(b,0,b.length);
            OutputStream os = cs.getOutputStream();
        }
    }

and this is my Server program:


    public class DA_FileServer {
        public static void main(String args[]) throws Exception{
            ServerSocket ss = new ServerSocket(5050);
            Socket cs = ss.accept();
            System.out.println("Connection Established!");

            byte[] b = new byte[12345];
            InputStream is = cs.getInputStream();
            FileOutputStream fos = new FileOutputStream("C:\\Users\\FoxSinOfGreed\\Desktop\\Destination.txt");
            is.read(b,0,b.length);
            fos.write(b,0,b.length);
        }
    }
    ```

P.S. I am using IntelliJ Idea Community Edition
user207421
  • 289,834
  • 37
  • 266
  • 440
  • I suspect it's because your client program is finishing, so it's closing the socket. – Jon Skeet Mar 29 '21 at 18:53
  • You forgot to close the socket in the client, so Windows reset the connection when the process ended. You also forget to *send* anything from the client, and to store and use the value returned by `FileInputStream.read()`. You can't assume it filled the buffer, and you can't assume it didn't return -1. – user207421 Mar 29 '21 at 22:08
  • @user207421 I just added this one line in the client program ( os.write(b,0,b.length); ) and it worked, lol. Tysm – FoxSinOfGreed Mar 30 '21 at 08:06
  • You should have added `os.close()` as well ... – user207421 Mar 30 '21 at 08:29

0 Answers0