套接字编程;通过多个设备传输时文件会损坏

时间:2015-10-06 00:42:57

标签: python sockets

我遇到的问题是跨设备从服务器到客户端获取文件。在localhost上一切正常。 让我们说"得到./testing.pdf"它将pdf从服务器发送到客户端。它发送但总是丢失字节。我如何发送数据有任何问题。如果是这样,我该如何解决?我省略了其他功能的代码,因为它们不用于此功能。

使用" hello"发送一个txt文件在它完美的工作

server.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()  

client.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 

1 个答案:

答案 0 :(得分:2)

我马上就能看到两个问题。我不知道这些是你遇到的问题,但它们都是问题。它们都与TCP是字节流而不是数据包流有关。也就是说,recv来电不一定与send来电一对一匹配。

  1. size = s.recv(1024)recv可能只返回部分大小的数字。此recv也可能会返回所有大小的数字加上一些数据。我会留下你来解决这个问题。

  2. data += s.recv(bufsize) / size -= bufsize无法保证recv调用返回bufsize字节。它可能返回比bufsize小得多的缓冲区。针对此案例的修复很简单:datum = s.recv(bufsize) / size -= len(datum) / data += datum