在Python中通过TCP套接字接收文件

时间:2018-02-08 19:34:59

标签: java python sockets tcp

我正在尝试通过TCP套接字将文件从Java客户端发送到Python服务器。我已经能够成功传输文件,但是服务器出现问题,它无法识别从客户端接收的字节流的结束。

这是我的服务器:

import socket

server_addr = '127.0.0.1', 5555

# Create a socket with port and host bindings
def setupServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created")
    try:
        s.bind(server_addr)
    except socket.error as msg:
        print(msg)
    return s


# Establish connection with a client
def setupConnection(s):
    s.listen(5)     # Allows five connections at a time
    print("Waiting for client")
    conn, addr = s.accept()
    return conn


def getFile(filename, conn):
    print("Creating file", filename, "to write to")
    with open(filename, 'wb') as f:
        data = conn.recv(1024)
        while data:
            print(data)
            f.write(data)
            data = conn.recv(1024)      #This is where the problem is
    print("Finished writing to file")


# Loop that sends & receives data
def dataTransfer(conn, s):
    while True:
        # Recieve a file
        print("Connected with:", s)
        filename = "test.json"
        getFile(filename, conn)
        break

    conn.close()


sock = setupServer()
while True:
    try:
        connection = setupConnection(sock)
        dataTransfer(connection, sock)
    except:
        break

这是Java客户端:

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

public class Client1
{
    private Socket socket = null;
    private FileOutputStream fos = null;
    private DataInputStream din = null;
    private DataOutputStream dos = null;
    private PrintStream pout = null;

    public Client1(InetAddress address, int port) 
    {
        try {
            System.out.println("Initializing Client");
            socket = new Socket(address, port);
            din = new DataInputStream(socket.getInputStream());
            dos = new DataOutputStream(socket.getOutputStream());
            pout = new PrintStream(socket.getOutputStream());
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            System.exit(1);
        }
    }

    public void send(String msg) throws IOException
    {
        pout.print(msg);
        pout.flush();
    }


    public void closeConnections() throws IOException
    {
        // Clean up when a connection is ended
        socket.close();
        din.close();
        dos.close();
        pout.close();
        scan.close();
    }


    public void sendFile(String filename)
    {
        System.out.println("Attempting to send file: "+filename);

        try{
            File file = new File(filename);
            if(!file.exists()){
                System.out.println("File does not exist. Aborting");
                return;
            }
            //send(filename);
            try (FileInputStream fis = new FileInputStream(file)) {
                int count;
                byte[] buffer = new byte[1024];

                while( (count = fis.read(buffer)) > 0){
                    dos.write(buffer, 0 ,  count);
                }
                dos.flush();
            }

        } catch(IOException e){
            e.printStackTrace();
        }
    }
}

问题是getFile()方法中服务器中的while循环。具体来说,while循环中的data = conn.recv(1024)似乎无限循环,data永远不会为空。 while循环的运行方式与读取while True:时的运行方式相同,但是一旦消息结束,它就会中断,然后关闭连接。正如我前面提到的,数据正确到达并且客户端干净利落,只是服务器无法检测到没有更多数据传入。

有关如何使此循环正常工作的任何建议吗?

0 个答案:

没有答案