通过套接字接收文件后没有收到任何进一步的消息

Not receiving any further messages after receiving a file over socket

我正在通过套接字从客户端向服务器发送文件。那工作正常。但是一旦收到文件,服务器程序就不会收到任何进一步的消息。它的所有接收都是空的。 这是客户端-服务器代码。

客户:

main(...){
  Socket sock = new Socket("127.0.0.1", 12345);
  File file = new File("file.txt");
  byte[] mybytearray = new byte[(int) file.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    bis.read(mybytearray, 0, mybytearray.length);
    OutputStream os = sock.getOutputStream();
    os.write(mybytearray, 0, mybytearray.length);

    PrintWriter out = new PrintWriter(os, true);
    out.println("next message");

    //closing here all streams and socket
}

服务器:

main(...){
 ServerSocket servsock = new ServerSocket(12345);
    while (true) {
        Socket sock = servsock.accept();
        byte[] mybytearray = new byte[1024];
        InputStream is = sock.getInputStream();
        Scanner scan1 = new Scanner(is);
        FileOutputStream fos = new FileOutputStream("myfile.txt");
        BufferedOutputStream bos = new BufferedOutputStream(fos);
        int bytesRead = is.read(mybytearray, 0, mybytearray.length);
        bos.write(mybytearray, 0, bytesRead);
        bos.close();
        fos.close();
        //Till here works fine, and file is successfully received.

        //Below is the code to receive next message. 
        //Unfortunately it is not working 
        BufferedReader input = new BufferedReader(new InputStreamReader(is));
        String line = input.readLine();
        System.out.println(line); //prints null, Whats the reason?
   }
}

基本问题是您假设 a) 当您阅读时您的文件恰好是 1024 字节长。 b)当您尝试读取时,您会一次性获得所有数据。写多了也最少1个字节

我推荐你

  • 随文件一起发送长度,以便您知道要阅读多少内容。
  • 您选择了二进制或文本,并且只选择了其中之一。

这是一个假设它是一个文件然后是一行文本的例子。在这两种情况下,我都先发送长度,这样它就可以作为字节数组处理。

服务器:

ServerSocket servsock = new ServerSocket(12345);
while (true) {
    Socket sock = servsock.accept();
    try (DataInputStream dis = new DataInputStream(sock.getInputStream())) {
        int len = dis.readInt();
        byte[] mybytearray = new byte[len];
        dis.readFully(mybytearray);
        try (FileOutputStream fos = new FileOutputStream("myfile.txt")) {
            fos.write(mybytearray);
        }
        len = dis.readInt();
        mybytearray = new byte[len];
        dis.readFully(mybytearray);
        String line = new String(mybytearray);
        System.out.println("line = " + line);
    }
}

客户:

Socket sock = new Socket("127.0.0.1", 12345);
File file = new File("file.txt");
byte[] mybytearray = new byte[(int) file.length()];
DataInputStream dis = new DataInputStream(new FileInputStream(file));
dis.readFully(mybytearray);
try(DataOutputStream os = new DataOutputStream(sock.getOutputStream())) {
    os.writeInt(mybytearray.length);
    os.write(mybytearray, 0, mybytearray.length);
    String nextMessage = "next message\n";
    byte message[] = nextMessage.getBytes();
    os.writeInt(message.length);
    os.write(message, 0, message.length);
}