我有一个任务,我应该制作 Napster 风格的点对点 (P2P) 文件共享系统。我同时使用了 rpyc 和面向消息的,但是当我从其他对等方下载文件时遇到问题 - 代码只是无限运行并且永不停止,没有输出。
Peer 有两个类 Client 和 server
from socket import *
import socket
import os
import pickle
import rpyc
from rpyc.utils.server import ThreadedServer
from const import *
类客户端():
conn = rpyc.connect(HOST, PORT) # Connect to the index_server
def lookUp(self,filename):
PeerList = self.conn.root.exposed_search(filename)
if PeerList==False:
print "no File with this Name"
else:
print PeerList
def register_on_server(self,Filename,port):
self.conn.root.exposed_register(Filename,port)
def download(self, serverhost, serverport, filename): # function download a file from another peer
sock.connect((serverhost,serverport))
print("Client Connected to download a file")
sock.send(pickle.dumps(filename))
localpath = "C:\Users\aa\PycharmProjects\task1\downloadfiles"
data = sock.recv(1024)
totalRecv = len(data)
f = open(localpath + '/' + filename, 'wb')
f.write(data)
filesize = os.path.getsize('C:\Users\aa\PycharmProjects\task1\uploadfiles' + '/' + filename)
while totalRecv < filesize:
data = sock.recv(1024)
totalRecv += len(data)
f.write(data)
print("File is downloaded Successfully")
sock.close()
类服务器(rpyc.Service):
def __init__(self, host, port):
self.host = host
self.port = port # the port it will listen to
global sock
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # socket for incoming calls
sock.bind((self.host, self.port)) # bind socket to an address
sock.listen(5) # max num connections
def obtain(self):
remotepath = "C:\Users\aa\PycharmProjects\task1\uploadfiles"
while True:
client, address = sock.accept()
print("Client Connected to download a file")
try:
filename = client.recv(1024)
if os.path.exists(remotepath + '/' + filename):
filesize = os.path.getsize(remotepath + '/' + filename)
if filesize > 0:
client.send(str(filesize))
with open(remotepath + '/' + filename, 'rb') as f:
bytes = f.read(1024)
client.send(bytes)
while bytes != "":
bytes = f.read(1024)
client.send(bytes)
else:
client.send("Empty")
else:
client.send("False")
except:
client.close()
return False
if __name__ == "__Server__":
server = ThreadedServer(Server, hostname=Server.host, port=Server.port)
server.start()
{Peer2}
from time import sleep
import rpyc
from peer import *
from const import *
peer2 = Client()
print ('1-register')
print ('2-search')
print ('3-download')
while(True):
commend = raw_input("enter your commend")
if commend == 'register':
filename = raw_input("write the file name")
peer2.register_on_server(filename,PeeR2PORT)
elif commend == 'search':
filename = raw_input("write the file name")
peer2.lookUp(filename)
elif commend == 'download':
port = raw_input("enter the other peer port")
host = raw_input("enter the other peer host")
filename = raw_input("enter the file name")
peer1 = Server(PeeR1HOST, PeeR1PORT)
peer1.obtain()
peer2.download(host, port, filename)