为什么文件不能完全传输?Python套接字编程

2024-09-27 04:23:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我遇到的问题是从服务器获取一个文件。假设我想 “快走/测试.pdf“它将pdf从服务器发送到客户端。它发送但总是缺少字节。我发送数据的方式有问题吗。如果是的话,我该怎么修?我省略了其他功能的代码,因为它们不用于此功能。你知道吗

你知道吗服务器.py你知道吗

import socket, os, subprocess          # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
#host = ''
port = 5000                # Reserve a port for your service.
bufsize = 4096
s.bind((host, port))        # Bind to the port
s.listen(5)                 # Now wait for client connection.

while True:
    c, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr

    while True:
      userInput = c.recv(1024)


    .... CODE ABOUT OTHER FUNCTIONALITY

      elif userInput.split(" ")[0] == "get":
      print "inputed get"
      somefile = userInput.split(" ")[1]
      size = os.stat(somefile).st_size
      print size
      c.send(str(size))

      bytes = open(somefile).read()
      c.send(bytes)
      print c.recv(1024)

c.close()  

你知道吗客户端.py你知道吗

import socket, os               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
#host = '192.168.0.18'
port = 5000                # Reserve a port for your service.
bufsize = 1

s.connect((host, port))

print s.recv(1024)
print "Welcome to the server :)"

while 1 < 2:
    userInput = raw_input()

   .... CODE ABOUT OTHER FUNCTIONALITY

    elif userInput.split(" ")[0] == "get":
        print "inputed get"
        s.send(userInput)
        fName = os.path.basename(userInput.split(" ")[1])
        myfile = open(fName, 'w')
        size = s.recv(1024)
        size = int(size)
        data = "" 

        while True:
            data += s.recv(bufsize)
            size -= bufsize
            if size < 0: break
            print 'writing file .... %d' % size

        myfile = open('Testing.pdf', 'w')
        myfile.write(data)
        myfile.close()
        s.send('success')

 s.close 

Tags: sendhostsizegetpdfosportsocket

热门问题