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

标签 java file sockets message

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

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

服务器:

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");
        }
}
}

客户:

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();
}
}

最佳答案

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

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"));
  }
}

和客户:

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"));
  }
}

您缺少的行是“socket.shutdownOutput()”。如果您离开该行,服务器将永远不会从 read 调用中看到文件结束标记 -1

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

关于java - 发送文件然后通过套接字发送消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6540787/

相关文章:

java - 寻找用Java处理CDA(AKA HL7v3,AKA CCD)消息的库

java - 单个线程应该只从连接池获取单个连接吗?

c++ - boost asio tcp 服务器

php - 可重复使用的 socket

java - Maven 资源自定义文件路径

java - javax.crypto.Cipher 的问题。解密字符串中的某些字符被破坏

java - 等待 Java 创建文件

file - 如何从 MS Word 创建 PCL 文件

c++ - Fstream管理问题

c++ - 将 C++ 套接字代码移植到 Windows