发送'浮动' Socket上的数据

时间:2016-10-15 15:17:45

标签: sockets python-3.x tcp

客户端将文件名发送给服务器。服务器为文件的所有实例爬网文件系统,并使用密钥作为绝对路径填充字典,并将值填充为文件大小。

我编写的代码似乎在逻辑上是正确的,但有时会成功运行,有时会出错。

服务器

import socket;
import sys;
import os;

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
host = socket.gethostname();
port = 49000;
serverSocket.bind((host, port));
serverSocket.listen(1);

while True:
  connectionSocket, address = serverSocket.accept();
  fileName = connectionSocket.recv(1024).decode();

  dictionary = {};

  for path, dirs, files in os.walk(os.path.abspath(os.sep)):
    for f in files:
      if f == fileName:
        dictionary[os.path.join(path, f)] = os.stat(f).st_size / 1024;

  if len(dictionary) == 0:
    connectionSocket.send(('0').encode());
    print();
    print('File not found!');
    sys.exit();
  else:
    connectionSocket.send(('1').encode());

  connectionSocket.send(str(len(dictionary)).encode());
  for key, value in dictionary.items():
    connectionSocket.send(key.encode('utf-16'));
    # If i don't write following line, error vanishes
    connectionSocket.send(str(value).encode('utf-16'));

  # File transfer
  f = open(fileName, 'rb');
  byte = f.read(1024);
  while (byte):
    #print('Sending...');
    connectionSocket.send(byte);
    byte = f.read(1024);
  f.close();
  print();
  print('Done sending.');
  connectionSocket.close();
  break;

客户端

import socket;
import sys;
import os;

if len(sys.argv) != 2:
  print();
  print('Invalid arguments!');
  sys.exit();

clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM);
host = socket.gethostname();
port = 49000;
clientSocket.connect((host, port));
clientSocket.send((sys.argv[1]).encode());

if clientSocket.recv(1024).decode() == '0':
  print();
  print('File not found!');
  sys.exit();

dictionary_size = int(clientSocket.recv(1024).decode());
for i in range(dictionary_size):
  print();
  print(clientSocket.recv(1024).decode('utf-16'));
  # If I don't write this line, error vanishes
  print(float(clientSocket.recv(1024).decode('utf-16')));

# File Transfer
byte = clientSocket.recv(1024);
f = open('Received_' + sys.argv[1], 'wb');
while (byte):
  #print ('Receiving...');
  f.write(byte);
  byte = clientSocket.recv(1024);
f.close();
print();
print('Done receiving.');
clientSocket.shutdown(socket.SHUT_WR);
clientSocket.close();

0 个答案:

没有答案