The codes below work if the computers are on the same network. However if these computers are on different networks, the connection timed out.
The codes of server.py are:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("192.168.1.**", 12345))
s.listen(10)
c, addr = s.accept()
print('{} connected.'.format(addr))
f = open("image.jpg", "rb")
datas = f.read(1024)
while datas:
c.send(datas)
datas = f.read(1024)
f.close()
print("Done sending...")
And the client.py includes:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("192.168.1.**", 12345))
f = open("recieved.jpg", "wb")
while True:
datas = s.recv(1024)
while datas:
f.write(datas)
datas = s.recv(1024)
f.close()
break
print("Done receiving")
I read that, the problem can rise from modem settings. Then i closed the firewall of the network which server.py connected on. But still the computer which client.py file is in, can't connect to the other computer.
What should i do, to connect these computers?
Thanks in advance.
Practical Data Science using Python The easiest way to copy files from one server to another over ssh is to use the scp command. For calling scp you'd need the subprocess module.
Try this:
server.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
import os
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(("", 12345)) #if the clients/server are on different network you shall bind to ('', port)
s.listen(10)
c, addr = s.accept()
print('{} connected.'.format(addr))
f = open("image.jpg", "rb")
l = os.path.getsize("image.jpg")
m = f.read(l)
c.send_all(m)
f.close()
print("Done sending...")
client.py:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(("server_public_ip", 12345)) # here you must past the public external ipaddress of the server machine, not that local address
f = open("recieved.jpg", "wb")
data = None
while True:
m = s.recv(1024)
data = m
if m:
while m:
m = s.recv(1024)
data += m
else:
break
f.write(data)
f.close()
print("Done receiving")
note: on your server.py you are waiting for 10 clients but you accept only one connection you shall put the c, addr = s.accept()
in a while
loop
Update: If the clients/server are behind a rooter then you have to forward the port on the rooter for that connection
Port Forwarding:
i've made myself a script to forward port on every OS but the script it too long you can grab it here
then in server.py:
from port_forwarding import forward_port
and before s = socket.socket ###
put
forward_port(port, 'description')
don't forget to put the port_forwarding script in the same folder of sever.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With