Python Socket connect two devices on same network - python

I am attempting to connect a simple server and client from two computers on the same network. Both the client and server cannot 'find' each other, as they do not move past .connect() and .accept() respectively. What am I doing wrong?
(Windows 10)
Server:
import socket
HOST = socket.gethostname() #Returns: "WASS104983"
#I have also tried socket.gethostbyname(socket.gethostname)), returning: "25.38.252.147"
PORT = 50007
sock = socket.socket()
sock.bind((HOST, PORT))
sock.listen(5)
print("Awaiting connection... ")
(clnt, addr) = sock.accept()
print("Client connected")
…
and Client:
import socket
HOST = "WASS104983" #Or "25.38.252.147", depending on the servers setup
PORT = 50007
sock = socket.socket()
print("Attempting connection... ")
sock.connect((HOST, PORT))
print("Connected")
…
I have gotten this to work before so I am not sure why it's not now.
I know there are a few questions of this calibre, but none seem to cover my problem.
Also, a wifi extender should not interfere with local transmissions should it?

I have always seen servers setup as such:
import socket
import threading
bind_ip = '0.0.0.0'
bind_port = 9999
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((bind_ip, bind_port))
server.listen(5)
print("[*] Listening on {}:{}".format(bind_ip, bind_port))
def handle_client(client_socket):
request = client_socket.recv(1024)
print('received: {}'.format(request))
client_socket.send(b'ACK!')
client_socket.close()
while True:
client, addr = server.accept()
print("[*] Accepted connection from: {}:{}".format(addr[0], addr[1]))
client_handler = threading.Thread(target=handle_client, args=(client,))
client_handler.start()*
Where I think an important distinction from your post may be that the server accepting connections is within an infinite loop. Have you tried this?

Related

Can't get client to connect to server

I'm just very confused still about the basic socket process. Tried multiple ways to try and get the socket to connect but it keeps refusing.
client code- socket_client.py
import socket
host = socket.gethostname()
port = 8080
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect((host,port))
res = client.send (b' testing data send...')
client.close()
server code- server_client.py
import socket
host = socket.gethostname()
port = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(10)
x=0
server_data = []
while True:
conn, addr = server.accept()
data = conn.recv(4096).decode()
x += 1
print ('Servicing client at %s'%addr[0])
server_data = client.recv(4096)
client_close()
server.close()
You have some problems in your server. You read from the connection but never use it, and you do client.recv when there is no variable client. This works:
import socket
host = socket.gethostname()
port = 8080
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind((host, port))
server.listen(10)
x=0
server_data = []
while True:
conn, addr = server.accept()
x += 1
print ('Servicing client at %s'%addr[0])
data = conn.recv(4096).decode()
print( "Received", data )
conn.close()
server.close()
Do remember that Python has a SocketServer module that can make some of this easier. If you need to get fancier, there are few modules better than Twisted at this kind of thing.
ALSO remember that the server must be running before you start the client. Someone has to be listening, otherwise the connection is rejected.

How to connect with Python Sockets to another computer on the same network

So I was trying to figure out a way to use sockets to make a terminal-based chat application, and I managed to do it quite well. Because I could only test it on one computer, I didn't realize that it might not work on different computers. My code is as simple as this:
# Server
import socket
HOST = "0.0.0.0"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print("Connected to", addr)
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(data)
# Client
import socket
HOST = "192.168.0.14"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello this is a connection")
data = s.recv(1024)
print("Received:", data.decode())
I've tried changing the ip to 0.0.0.0, use gethostname a lot of other things, but it just doesn't work. The server is up and running, but the client can't connect. Can someone help me?
I believe that 0.0.0.0 means connect from anywhere which means that you have to allow port 5555 through your firewall.
Instead of 0.0.0.0 use localhost as the address in both the client and the server.
I just tested your code using localhost for the server and the client and your program worked.
server:
Connected to ('127.0.0.1', 53850)
Received: Hello this is a connection
client:
Received: Hello this is a connection
As you can see, all that I changed was the address on both the server and the client. If this doesn't work then there is something outside of your program that is preventing you from success. It could be a permissions issue or another program is listening on port 5555.
server.py
# Server
import socket
HOST = "0.0.0.0"
HOST = "localhost"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((HOST, PORT))
s.listen()
while True:
conn, addr = s.accept()
with conn:
print("Connected to", addr)
data = conn.recv(1024)
print("Received:", data.decode())
conn.sendall(data)
if __name__ == '__main__':
pass
client.py
# Client
import socket
HOST = "localhost"
PORT = 5555
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect((HOST, PORT))
s.sendall(b"Hello this is a connection")
data = s.recv(1024)
print("Received:", data.decode())
if __name__ == '__main__':
pass

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: simple client server the listening for connections close after first connection close

So i want to build simple Server-Client.
This server gets connections from clients (simple string), do my stuff, return answer, close the client connection and wait for another connections.
Client
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ip = '127.0.0.1'
port = 4500
address = (ip, port)
message = 'mymessage'
client = socket.socket()
client.connect(address)
client.sendall(message.encode('utf-8'))
Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
name = socket.gethostname()
ip = '127.0.0.1'
port = 4500
address = (ip, port)
server.bind(address)
server.listen(1)
print('Start listening on', ip, ':', port)
client, addr = server.accept()
print('Received connection from', addr[0], ':', addr[1])
while True:
data = client.recv(1024).decode('utf-8')
print('Received', data, 'from the client')
# DO something.....
client.send('Goodbye'.encode('utf-8'))
client.close()
break
So currently after the client get back the response from the server the server is close and i want my server to continue listening for another connections.
Simple, you need to add another loop, so that the server can always listen:
Server
import socket
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
name = socket.gethostname()
ip = '127.0.0.1'
port = 4500
address = (ip, port)
server.bind(address)
server.listen(1)
while True:
client, addr = server.accept()
print('Start listening on', ip, ':', port)
print('Received connection from', addr[0], ':', addr[1])
while True:
data = client.recv(1024).decode('utf-8')
print('Received', data, 'from the client')
# DO something.....
client.send('Goodbye'.encode('utf-8'))
client.close()
break

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.

Categories