如何重新打开已关闭的套接字以便将消息发送回客户端

时间:2013-09-24 02:05:29

标签: java android sockets networking tcp

使用DataInputStream获取从Android客户端发送到此Java桌面服务器的int和long。之后,从Android客户端收到pdf文件。客户端发送给服务器的总共3个文件。问题是在向另一个方向发送时。

我必须在while循环后立即关闭输入和输出流。如果我不这样做,pdf文件将被破坏,程序将停止并停留在while循环中,而不是继续执行到线程的末尾。

如果我必须关闭输入和输出蒸汽,则套接字将关闭。我如何重新打开同一个插座?

我需要重新打开同一个套接字,因为需要将一条消息发送回服务器收到pdf文件的Android客户端,以便向服务器发送确认文件已安全接收。

有多个Android客户端连接到同一个Java服务器,因此我想要将消息发送回客户端需要相同的套接字。没有套接字,很难确定将消息发送到哪个客户端。

       byte[] buffer = new byte[fileSizeFromClient];

        while((count = dis.read(buffer)) > 0){
            bos.write(buffer, 0, count);
        }

       dis.close();  // closes DataInputStream dis
       bos.close();  // closes BufferedOutputStream bos

编辑:

来自客户端的

代码

   dos.writeInt((int)length); // sends the length as number bytes is file size to the server
   dos.writeLong(serial); // sends the serial number to the server

                int count = 0; // number of bytes

                while ((count = bis.read(bytes)) > 0) {
                    dos.write(bytes, 0, count);
                }

     dos.close(); // need to close outputstream or result is incomplete file sent to server
                  // and the server hangs, stuck on the while loop
                  // if dos is closed then the server sends error free file

1 个答案:

答案 0 :(得分:1)

没有。你无法重新打开套接字。你必须做一个新的。完成文件传输后,您不必关闭套接字。服务器仍然可以重复使用它发送消息回复。由于您已经发送了文件大小,因此您的服务器可以使用它来了解客户端何时完成发送完整文件。之后,您的服务器可以将您的回复发送给客户端。

尝试使用当前循环。

 int bytesRead = 0;
 while((count = dis.read(buffer)) > 0 && bytesRead != fileSizeFromClient){
  bytesRead += count; 
  bos.write(buffer, 0, count);
 }
 bos.close();
 //don't close the input stream