java 通过套接字发送文件然后消息

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6540787/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 16:16:51  来源:igfitidea点击:

send file then message through socket

javafilesocketsmessage

提问by ophelie88

I am trying to send a file from a client to a server. The server receives the file and then send a confirmation message to the client.

我正在尝试将文件从客户端发送到服务器。服务器接收文件,然后向客户端发送确认消息。

My problem is that the client becomes unresponsive when it is waiting the confirmation.

我的问题是客户端在等待确认时变得没有响应。

Server :

服务器 :

import java.net.*;
import java.io.*;

public class Server {
public static void main(String args[]) throws IOException {
        int port = 1234;
    ServerSocket server_socket;

    server_socket = new ServerSocket(port);
    System.out.println("Server waiting for client on port "
            + server_socket.getLocalPort());
    // server infinite loop
    while (true) {
        Socket socket = server_socket.accept();
        System.out.println("New connection accepted "
                + socket.getInetAddress() + ":" + socket.getPort());
    try {
                byte[] b = new byte[1024];
                int len = 0;
                int bytcount = 1024;
                String FileName = "C:\test\java\tmp\sentfile.pdf"; 
                FileOutputStream inFile = new FileOutputStream(FileName);
                InputStream is = socket.getInputStream();
                BufferedInputStream in2 = new BufferedInputStream(is, 1024);
                while ((len = in2.read(b, 0, 1024)) != -1) {
                    bytcount = bytcount + 1024;
                inFile.write(b, 0, len);
                }
                System.out.println("Bytes Writen : " + bytcount);

                //Sending the response back to the client.
                ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
                oos.flush();
                oos.writeObject("ok");
                System.out.println("Message sent to the client is "+"ok");

                in2.close();
                inFile.close();
            } catch (IOException e) {
        System.out.println("Unable to open file" + e);
        return;
    }
    socket.close();
    System.out.println("Connection closed by client");
        }
}
}

Client :

客户 :

import java.net.*;
import java.io.*;

public class Client {
    public static void main(String[] args) throws UnknownHostException,
        IOException, ClassNotFoundException {

        int port = 1234;
    Socket socket = null;

    // connect to server
    socket = new Socket("127.0.0.1", port);

    try {
            byte[] buf = new byte[1024];
            OutputStream os = socket.getOutputStream();
            BufferedOutputStream out = new BufferedOutputStream(os, 1024);
            String file = "C:\test\java\client\source.pdf"; 
            FileInputStream in = new FileInputStream(file);
            int i = 0;
            int bytecount = 1024;
            while ((i = in.read(buf, 0, 1024)) != -1) {
                bytecount = bytecount + 1024;
            out.write(buf, 0, i);
            out.flush();
            }
            System.out.println("Bytes Sent :" + bytecount);

            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            String confirmation = (String) ois.readObject();
            System.out.println("from server : " + confirmation);

            out.close();
            in.close();
    } catch (IOException e) {
    System.out.println(e);
    }
    socket.close();
}
}

回答by Roland Illig

Here is the complete working example. The server:

这是完整的工作示例。服务器:

package so6540787;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

  private final Socket socket;

  public Server(Socket socket) {
    this.socket = socket;
  }

  public void receiveFile(File file) throws IOException {
    byte[] b = new byte[1024];
    int len = 0;
    int bytcount = 1024;
    FileOutputStream inFile = new FileOutputStream(file);
    InputStream is = socket.getInputStream();
    BufferedInputStream in2 = new BufferedInputStream(is, 1024);
    while ((len = in2.read(b, 0, 1024)) != -1) {
      bytcount = bytcount + 1024;
      inFile.write(b, 0, len);
    }
    System.out.println("Bytes Writen : " + bytcount);

    // Sending the response back to the client.
    ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
    oos.flush();
    oos.writeObject("ok");
    System.out.println("Message sent to the client is " + "ok");

    in2.close();
    inFile.close();
  }

  public static void main(String[] args) throws IOException {
    ServerSocket listen = new ServerSocket(10000, 1);
    Socket socket = listen.accept();
    Server server = new Server(socket);
    server.receiveFile(new File("c:/received.pdf"));
  }
}

And the client:

和客户:

package so6540787;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.OutputStream;
import java.net.Socket;

public class Client {

  private final Socket socket;

  public Client(Socket socket) {
    this.socket = socket;
  }

  public void sendFile(File file) throws IOException, ClassNotFoundException {
    byte[] buf = new byte[1024];
    OutputStream os = socket.getOutputStream();
    BufferedOutputStream out = new BufferedOutputStream(os, 1024);
    FileInputStream in = new FileInputStream(file);
    int i = 0;
    int bytecount = 1024;
    while ((i = in.read(buf, 0, 1024)) != -1) {
      bytecount = bytecount + 1024;
      out.write(buf, 0, i);
      out.flush();
    }
    socket.shutdownOutput(); /* important */
    System.out.println("Bytes Sent :" + bytecount);

    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
    ois.skip(Long.MAX_VALUE);
    String confirmation = (String) ois.readObject();
    System.out.println("from server : " + confirmation);

    out.close();
    in.close();
  }

  public static void main(String[] args) throws IOException, ClassNotFoundException {
    Client client = new Client(new Socket("localhost", 10000));
    client.sendFile(new File("c:/tobesent.pdf"));
  }
}

The line you were missing is the "socket.shutdownOutput()". If you leave that line out, the server will never see the end-of-file marker -1from the readcall.

您缺少的那一行是“socket.shutdownOutput()”。如果您省略该行,服务器将永远不会看到-1来自read调用的文件结束标记。

Please fix the way you count the bytes that have been sent. You should really start with 0 instead of 1024 and only increment that counter by as many bytes as you have actually read.

请修正您计算已发送字节数的方式。你真的应该从 0 而不是 1024 开始,并且只增加你实际读取的字节数。

回答by artbristol

Use HTTP! It's designed for exactly this type of problem. There are loads of HTTP client and server libraries freely available for Java.

使用 HTTP!它专为此类问题而设计。有大量可免费用于 Java 的 HTTP 客户端和服务器库。