2

I am trying to send file from java app to a remote c# application through socket here is the code C#

TcpClient tcpClient = new TcpClient();
                tcpClient.Connect(ip, 1593);
                NetworkStream networkStream = tcpClient.GetStream();
                StreamReader sr = new StreamReader(networkStream);
                //read file length
                int length = int.Parse(sr.ReadLine());

                byte[] buffer = new byte[length];
                networkStream.Read(buffer, 0, (int)length);
                //write to file
                BinaryWriter bWrite = new BinaryWriter(File.Open(strFilePath, FileMode.Create));
                bWrite.Write(buffer);
                bWrite.Flush();
                bWrite.Close();
                tcpClient.Close();

Java app

ServerSocket serverSocket = new ServerSocket(1593);
            System.out.println("Server started and waiting for request..");
            Socket socket = serverSocket.accept();
            System.out.println("Connection accepted from " + socket);
            PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
            File file = new File(strFileToSend);
            // send file length
            out.println(file.length());
            // read file to buffer
            byte[] buffer = new byte[(int) file.length()];
            DataInputStream dis = new DataInputStream(new FileInputStream(file));
            dis.read(buffer, 0, buffer.length);
            // send file
            BufferedOutputStream bos = new BufferedOutputStream(
                    socket.getOutputStream());
            bos.write(buffer);
            bos.flush();
            serverSocket.close();
            System.out.println("File has been send ... ");

The exception raised from the client side

Unable to read data from the transport connection : An existing connection was forcibly closed by the remote host

The server application said it has sent successfully the file. Thanks in advance.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142
Maher HTB
  • 737
  • 3
  • 9
  • 23
  • http://stackoverflow.com/questions/2582036/an-existing-connection-was-forcibly-closed-by-the-remote-host – Kadaj May 11 '17 at 14:09

1 Answers1

1

Your problem is that you are issuing serverSocket.close(); too soon. The Server Socket is not supposed to be closed just because a single transaction between the client and the server concluded. The server socket is supposed to stay open for as long as the server is running.

So, when you close the server socket, the response to the client is still in transit, (it probably hasn't even begun transmitting yet from the server to the client,) so the client gets disconnected prematurely, before it has had the chance to receive or fully process the response.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142