下面粘贴的是我的客户端和服务器 python 脚本。TCP 连接建立良好。服务器很好听。暂时,我已经把我的电脑客户端和服务器都做了。基本上,我没有收到文件。客户端只是说接收文件,然后仅此而已。服务器也只是在听。什么都不承认。看看我打开文件的方式并指导我完成这个。
SERVER.py
import socket
import sys
import os.path
import operator
serverPort = 5005
#create socket object for server
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverSocket.bind(('192.168.1.8',serverPort))
serverSocket.listen(1)
print ('Server listening...')
print (socket.gethostbyname(socket.gethostname()))
while True:
#return value of accept() is assigned to socket object
#and address bound to that socket
connectionSocket, addr = serverSocket.accept()
#connection established with client
print ('Got connection from', addr)
print ('Awaiting command from client...')
client_request = connectionSocket.recv(1024)
file_name = client_request.recv(1024)
f = open(file_name, "rb")
print('Sending file...')
l = f.read(1024)
while(l):
connectionSocket.send(l)
l = f.read(1024)
f.close()
print('Done sending')
connectionSocket.close()
而客户端脚本如下:
import socket
import sys
serverName = '192.168.1.8'
serverPort = 49675
#in this loop, sockets open and close for each request the client makes
#while True:
#create socket object for client
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientSocket.connect((serverName,serverPort))
print('Connected to server.')
fileName = "C:\\Users\\dell\\Desktop\\mano.txt"
clientSocket.send(fileName)
#if sentence == 'GET':
f = open(fileName, "wb")
print('Receiving file..')
l = clientSocket.recv(1024)
while (l):
f.write(l)
l = clientSocket.recv(1024)
f.close()
print('Done receiving file')
clientSocket.close()