使用套接字从远程主机(Python)访问文件

问题描述 投票:0回答:1

下面粘贴的是我的客户端和服务器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()
python sockets file-transfer remote-host
1个回答
1
投票

偶然发现,OP可能自己解决了这个问题,以防万一。在这里我看到的是,OP在这里犯了几个错误。

  1. 如Stevo所述,Sever和Client中使用的端口号应为相同的端口号,在这种情况下,5005或49675都可以使用。实际上,任何其他大于1024的端口号都可以,因为操作系统通常会限制使用低于该端口号的端口。https://hub.packtpub.com/understanding-network-port-numbers-tcp-udp-and-icmp-on-an-operating-system/您可以在此链接中了解端口号和相关内容。
  2. 您的服务器文件本身有编码错误。您首先必须在print ('Awaiting command from client...')之后的所有行缩进,并将其缩进对齐。代码只是停留在while True:循环中,除了打印这两行print ('Got connection from', addr)print ('Awaiting command from client...')外,基本上没有任何意义。而且,您的client_request是一个字节对象,字节对象不包含recv方法的方法。

更改了服务器端的小错误后,我便可以运行它并接收来自客户端的消息。This is what it looks like。可能此页面可能有所帮助:https://docs.python.org/3/library/socket.html

© www.soinside.com 2019 - 2024. All rights reserved.