python 3.4.3文件没有完整地编写

时间:2015-10-14 07:41:14

标签: python

以下是完整的客户端,服务器和sendproc代码:

Client.py

      from socket import *
      import pickle
      import sendproc
      import struct

      s = socket(AF_INET, SOCK_STREAM)            # Create a socket object
      host = "192.168.1.4"       # Get local machine name
      port = 1094                # Reserve a port for your service.
      s.connect((host, port))

      with open("file.txt",'rb') as f:
      print ('file opened')
      print('Sending file...')
      for data in f:
        print(data)
        print("MSG sent")
        sendproc.send_msg(s, data) 

Server.py

       from socket import *
       import pickle
       import sendproc

       port = 1094                             # Reserve port for  service.
       s = socket(AF_INET,SOCK_STREAM)             # Create a socket object
       host = "192.168.1.4"    # Get local machine name
       s.bind((host, port))            # Bind to the port
       s.listen(5)
       print('server is listening')
       conn,addr = s.accept()


       with open("file1.txt",'w') as fb:
           print("File downloading\n",fb)
           while True:
              print("hi")
              data = sendproc.recv_msg(conn)
              print(data)
              if not data:
                   print("No data")
                   break
              fb.write(data)

              fb.flush()
       print("Download complete\n")

SendRecieveProcedure.py

 import struct

def send_msg(s, msg):
msg2 = struct.pack('>I', len(msg)) + msg 
s.send(msg2)

def recv_msg(s):
# Read message length and unpack it into an integer
raw_msglen = s.recv(4)
print(raw_msglen)

if not raw_msglen:
    return None
n = struct.unpack('>I',raw_msglen)[0]
# Read the message data
data = ' '
while len(data) < n:
    packet = s.recv(n - len(data)).decode("cp437")

    if not packet:
        return None
    data += packet
    #print("hwllo",data )
return data

输出正确打印到控制台,但是如果我打开文件,它只会写出起始行。那么代码中的问题是什么

0 个答案:

没有答案