Reputation: 140
Hi i made this file server app and i opened the server in one laptop, and opened the client program in another laptop but i couldn't connect to the server. both laptops are connected to same wifi so shouldn't it be working? and if i open the server and client program in one laptop, the client can connect to server.
here's my code
Server
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()
Client
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()
Upvotes: 1
Views: 6698
Reputation: 6103
You seem to be misunderstanding the meaning of "localhost". It always, only refers to the exact computer you're on. So for the client, "localhost" resolves to itself, and on the server "localhost" refers to itself. Hence, the client looks for the server running on its own computer at port 5123, which of course fails because the server isn't running on its same computer, it's running somewhere else. That's also why the code works when the server and the client are both on the same machine.
You need to get the ip address or hostname of the server laptop in order to connect to it from the client. You can get this by running hostname
on the server computer in a linux terminal or windows command line, and putting that name instead of "localhost"
into the code that's running on the client computer.
E.g., on the server laptop in a terminal:
$ hostname
myserver
And in your client code:
host = socket.gethostbyname("myserver")
Upvotes: 1