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

时间:2015-09-12 20:57:55

标签: java serversocket

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

客户端:

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?
   }
}

2 个答案:

答案 0 :(得分:1)

基本问题是你假设a)当你阅读时你的文件正好是1024字节长。 b)当您尝试阅读时,您可以一次性获取所有数据。即使你写了更多内容,最小值也是1个字节。

我建议你

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

答案 1 :(得分: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);
}