读写文件后文件格式不兼容

时间:2018-09-24 19:17:46

标签: python python-3.x

服务器:

import socket

HOST = ''
PORT = 9876
ADDR = ("127.0.0.1",4444)
BUFSIZE = 4096

serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

serv.bind(ADDR)
serv.listen(5)

print('listening ...')
conn, addr = serv.accept()
print('client connected ... ', addr)

def download():
  while True:
    print("Got succesfully to the function")
    data = conn.recv(BUFSIZE)
    if not data: break
    myfile = open(command[1], 'wb')
    print(data)
    myfile.write(data)
    print ('writing file ....')
    myfile.close()
    print ('finished writing file')



while True:
  command = input(">> ") #Basicamente lo que esta pasando aqui:
  command = command.encode() #Se encodea para mandarlo
  conn.send(command) #Se manda bien
  command = command.decode() #Se desencodea
  command = command.split(" ") #Y se hace en una lista para los "ifs"
  data = conn.recv(BUFSIZE)
  print("Recieved package")
  if command[0] == "download":
    download()
  else:
    print(data)

conn.close()

print ('client disconnected')

客户:

import socket

HOST = 'localhost'
PORT = 9876
ADDR = ("127.0.0.1",4444)
BUFSIZE = 4096
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(ADDR)

recibio = client.recv(BUFSIZE).decode()
recibio = recibio.split(" ")


def mandar_archivo():   
    bytes = open(recibio[1], 'rb').read()
    print(recibio[1])
    print(len(bytes))
    client.sendall(bytes)

mandar_archivo()
client.close()

这实际上是该程序第一次实际发送数据。昨天,它发送了empy字节。今天,它确实可以工作,唯一的问题是,当我尝试打开文件时,例如说一个.jpg,它告诉我它不兼容。数据正在以utf-8编码发送。

非常感谢。

0 个答案:

没有答案