How to connect 2 computers on diffrent networks using python sockets - python

I'm trying to connect 2 different computers that on different networks,
but I got an error:
TimeoutError: [Errno 110] Connection timed out
And sometimes I got this error:
OSError: [Errno 113] No route to host
I wrote the server.py script and started it on the first pc and client.py on the second one.
server.py
import socket
server_socket = socket.socket()
server_socket.bind(("127.0.0.1", 80))
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
print ("client_connected [" + client_address[0] + "]")
client_command = client_socket.recv(1024).decode()
print(client_command.encode())
client.py
import socket
client_socket = socket.socket()
client_socket.connect(("server_public_ip_here", 8820))
client_command = input("command: ")
client_socket.send(client_command.encode())
data = client_socket.recv(1024).decode()
print("server: " + data)
I expect to get a connections between the computers but keep getting a TimeoutError or OSError

if you are on two separate computers you should bind to 0.0.0.0 (to listen to all network connections) or to the server's IP for connections on that IP, and not 127.0.0.1 (localhost). Works if client and server are both in the same machine. Also you should use the same port on client and server.
I test it and it worked:
server.py
import socket
server_socket = socket.socket()
server_socket.bind(("0.0.0.0", 8000))
server_socket.listen(1)
(client_socket, client_address) = server_socket.accept()
print ("client_connected [" + client_address[0] + "]")
client_command = client_socket.recv(1024).decode()
print(client_command.encode())
client.py
import socket
client_socket = socket.socket()
client_socket.connect(("127.0.0.1", 8000)) #or enter ip of server
client_command = input("command: ")
client_socket.send(client_command.encode())
data = client_socket.recv(1024).decode()
print("server: " + data)

Related

nonstop server client connection[Python]

I want to create a server-client connection that the client can always be connected to the server. How can I do it? Please help me. when I was trying, this error occurred.
"ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host"
- code -
server:
import socket
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
conn, addr=s.accept()
while True:
conn.send(("Test message").encode())
print((conn.recv(1024)).decode())
except Exception as error:
print(str(error))
client:
import socket
try:
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((server_host,port))
while True:
print((s.recv(1024)).decode())
s.send(("Test message").encode())
except Exception as error:
print(str(error))
Some reasons cause this error message:
Server reused the connection because it has been idle for too long.
May be Client IP address or Port number not same as Server.
The network between server and client may be temporarily going down.
Server not started at first.
Your code seems to be OK. Did you run the Server at first time then client? Please make sure it. The below code fully tested on my computer.
Server:
import socket
HOST = '127.0.0.1' # (localhost)
PORT = 65432 # Port to listen on
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
conn, addr = s.accept()
while True:
data = conn.recv(1024).decode()
if not data:
break
conn.send(data.encode())
Client
import socket
HOST = '127.0.0.1' # Server's IP address
PORT = 65432 # Server's port
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
while True:
s.send(("Hi server, send me back this message please").encode())
data = s.recv(1024).decode()
print('(From Server) :', repr(data))
Note: Run the Server first then Client.
Output:

Python socket.error: [Errno 32] Broken pipe

i made a python listener(server) on my vps
but when i give the server and client the ip addreess of vps and port 8585
this error shows:
error :
socket.error: [Errno 32] Broken pipe
i use python version 2 in vps
i use python version 3 in my PC
my server code :
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
ip = raw_input("ip : ")
ip = str(ip)
port = raw_input("port : ")
port = int(port)
s.bind((ip,port))
s.listen(5)
while True:
c, addr = s.accept()
s.send("welcome !")
print (addr, "connected.")`
client :
import socket
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
HOST = input("HOST : ")
HOST = str(HOST)
PORT = input("PORT : ")
PORT = int(PORT)
s.connect((HOST,PORT))
buff = 1024
data = s.recv(buff)
print(data)`
In the server you have:
c, addr = s.accept()
s.send("welcome !")
You must do the send on the connected socket to the client and not on the listener socket, i.e. it should be c.send instead of s.send.

python socket server over internet

So i would like to create a small online game. (I am a complete noob with networking)
I got a server-client connection going if they are both on the same network but would need to do it over the internet. How do i do this?
server.py
import socket
s = socket.socket()
host = "0.0.0.0"
port = 5000
s.bind((host,port))
s.listen(5)
while True:
c, addr = s.accept()
print("Connection from", addr)
c.close()
client.py
import socket
s = socket.socket()
host = "192.168.1.66"
port = 5000
s.connect((host, port))
s.send(bytearray("Message", "ascii"))
I have tried using my public IP but i cannot connect.

Setting up Python UDP server between two computers on same Wi-Fi network

I am trying to set up a UDP client-server connection between two laptops.
Server code:
import socket
def Main():
host = '8.8.8.8'
port = 8000
s = socket.socket()
s.bind((host,port))
s.listen(2)
c, addr = s.accept()
print("Connection from: " + str(addr))
while True:
data = c.recv(1024)
if not data:
break
print("from connected user: " + str(data))
data = str(data).upper()
print("sending: " + str(data))
c.send(str.encode(data))
c.close()
client:
import socket
def Main():
host = '8.8.8.8'
port = 8000
s = socket.socket()
print ('Created socket')
s.connect((host, port))
print ('Connected to host')
message = input("-> ")
while message != 'q':
s.send(str.encode(message))
data = s.recv(1024)
print("Received from server: " + str(data))
message = input("-> ")
s.close()
I was able to get this working on one laptop i.e I opened two terminals and got a working connection, but when I try and to it between two laptops, the client times out while trying to connect to the server. Based on my research as long as I don't use the IP '127.0.0.1' it should work. Any idea what could fix this?

Socket.error: [Errno 10022] An invalid argument was supplied

#!/usr/bin/env python
import socket
clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect(('192.168.1.123', 5162))
clientsocket.send('getval.1')
clientsocket.close
clientsocket.bind(('192.168.1.124', 5163))
clientsocket.listen(1)
while True:
connection, address=clientsocket.accept()
value=connection.recv(1024)
print value
I'm trying to get python to send a message to the server, and in return the server responds. Yet when I execute this code it gives me
Socket.error: [Errno 10022] An invalid argument was supplied
It seems you wrote a mixed code of server and client
Here a simple sample of codes for socket programming the first on server side and the second on client
Server side code:
# server.py
import socket
import time
# create a socket object
serversocket = socket.socket(
socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# bind to the port
serversocket.bind((host, port))
# queue up to 5 requests
serversocket.listen(5)
while True:
# establish a connection
clientsocket,addr = serversocket.accept()
print("Got a connection from %s" % str(addr))
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode('ascii'))
clientsocket.close()
and now the client
# client.py
import socket
# create a socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# get local machine name
host = socket.gethostname()
port = 9999
# connection to hostname on the port.
s.connect((host, port))
# Receive no more than 1024 bytes
tm = s.recv(1024)
s.close()
print("The time got from the server is %s" % tm.decode('ascii'))
The server simply remained listened for any client and when it finds out a new connection it returns current datetime and closes the client connection

Categories