嗨,我制作了这个文件服务器应用程序,我在一台笔记本电脑中打开了服务器,在另一台笔记本上打开了客户端程序,但是我无法连接到服务器。这两台笔记本电脑都连接到同一个wifi上,所以它不应该工作吗?如果我在一台笔记本电脑中打开服务器和客户端程序,客户端就可以连接到服务器。
这是我的密码
服务器
import threading
import os
import socket
def RetrFile(name, sock):
filename = str(sock.recv(1024), 'utf-8')
print(filename)
if os.path.isfile(filename):
sock.send(bytes("EXISTS" + str(os.path.getsize(filename)), 'utf-8'))
userResponse = str(sock.recv(1024), 'utf-8')
if userResponse[:2] == 'Ok':
with open(filename, 'rb') as f:
bytesToSend = f.read(1024)
sock.send(bytesToSend)
while bytesToSend != "":
bytesToSend=f.read(1024)
sock.send(bytesToSend)
else:
sock.send(bytes("ERR", 'utf-8'))
sock.close()
def Main():
host = socket.gethostbyname("localhost")
port = 5123
s = socket.socket()
s.bind(('0.0.0.0', port))
s.listen(5)
print("Server started")
while True:
c, addr = s.accept()
print("Client connected" + str(addr))
t = threading.Thread(target=RetrFile, args=("rthread", c))
t.start()
s.close()
Main()客户端
import socket
def Main():
host = socket.gethostbyname("localhost")
port = 5123
s= socket.socket()
s.connect((host, port))
filename = input("Filename? ->")
if filename != 'q':
s.send(bytes(filename,'utf-8'))
data=str(s.recv(1024),'utf-8')
if data[:6] == 'EXISTS':
filesze = data[6:]
message = input("File Exists" + filesze + "(Y/N)")
if message == 'Y':
s.send(bytes("Ok",'utf-8'))
f = open('new_'+filename, 'wb')
data = s.recv(1024)
total = len(data)
f.write(data)
while total < int(filesze):
data = s.recv(1024)
total+= len(data)
f.write(data)
print('%.2f' %((total/int(filesze)*100)), " percentage complted ")
print("Download Complete")
else:
print("doesnt exist")
s.close()
Main()发布于 2018-05-07 21:33:51
你似乎误解了"localhost“的意思。它总是,只指你所使用的电脑。因此,对于客户端,"localhost“解析为自身,而在服务器上,"localhost”指的是自身。因此,客户机在端口5123寻找在自己的计算机上运行的服务器,这当然会失败,因为服务器不是在同一台计算机上运行,而是在其他地方运行。这也是为什么当服务器和客户端都在同一台机器上时,代码才能工作。
您需要获取服务器膝上型计算机的ip地址或主机名,以便从客户端连接到它。您可以通过在linux终端或windows命令行中的服务器计算机上运行hostname,并将该名称而不是"localhost"放入在客户端计算机上运行的代码中来实现这一点。
例如,在终端的服务器膝上型计算机上:
$ hostname
myserver在你的客户代码中:
host = socket.gethostbyname("myserver")https://stackoverflow.com/questions/50222673
复制相似问题