Joe
Joe

Reputation: 116

Python 3 socket client not connecting to server

I have a server.py and client.py pair. When I run the server on my machine and open multiple terminals to runs clients, I can connect fine. But when I try to run clients on another computer, the client never connects to the server. I'm pretty sure I tested this code a few months ago on multiple computers and it worked fine (though maybe I'm remembering wrong), but I think I updated my python version, so maybe that's why? How can I change my code below so it works?

server.py

import socket
from threading import Thread
import sys

clients = []

def recv(clientsocket):
    while True:
        msg = clientsocket.recv(1024) # wait for message from any of the clients.
        print("\n" + msg.decode())
        for c in clients: # send to all the clients.
            c.send(msg)

def send(clientsocket):
    while True:
        msg = "[Server] %s" % input("\n") # wait for input
        print(msg)
        for c in clients: # send to all the clients.
            c.send(msg.encode())
    clientsocket.close()

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create a socket object
host = socket.gethostname() # Get local machine name
#port = 3001                 # Reserve a port for your service.
port = int(input("Enter port: "))

print ('Server started at [%s]' % socket.gethostbyname(host))
print ('Waiting for clients...')

#s.bind((host, port))       # Bind to the port
s.bind((socket.gethostbyname(host), port))
s.listen(5)                 # Now wait for client connection.

while True:
    #Waits until someone new to accept
    c, addr = s.accept()
    print(addr, "connected.")
    clients.append(c)
    thread_recv = Thread(target=recv, args=((c,)))
    thread_recv.start()

    thread_send = Thread(target=send, args=((c,)))
    thread_send.start()


s.close()

client.py

import socket
from threading import Thread

hostname = input("Enter hostname/IP to connect to: ")
# port = 3001
port = int(input("Enter port: "))

clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsocket.connect((hostname, port))

def recv():
    while True:
        print("\n" + clientsocket.recv(2048).decode())

def send(username):
    while True:
        msg = "[%s] %s" % (username, input(""))
        clientsocket.send(msg.encode()) # send message to the server.

username = input("Choose a username: ")
msg = "[%s has just connected]" % (username)
clientsocket.send(msg.encode())

thread_send = Thread(target=send, args=(username,))
thread_send.start()
thread_recv = Thread(target=recv, args=())
thread_recv.start()

while True:
    # keep the threads going.
    pass

Edit Every time I start the server, it says my ip address is the same: 192.168.56.1. Even though I've turned my computer off and tried again. But when I go to Google and ask what is my ip address, it is something totally different. Why does the socket keep choosing 192.168.56.1? Is there something special about it? Is this something related to my problem?

Upvotes: 1

Views: 2282

Answers (1)

JoshuaCS
JoshuaCS

Reputation: 2624

Just bind you server to 0.0.0.0 and bind it to all network interfaces:

server.py

s.bind(('0.0.0.0', port))

Then the code in server.py will end up being something like this:

    import socket
    from threading import Thread
    import sys

    clients = []

    def recv(clientsocket):
        while True:
            msg = clientsocket.recv(1024) # wait for message from any of the clients.
            print("\n" + msg.decode())
            for c in clients: # send to all the clients.
                c.send(msg)

    def send(clientsocket):
        while True:
            msg = "[Server] %s" % input("\n") # wait for input
            print(msg)
            for c in clients: # send to all the clients.
                c.send(msg.encode())
        clientsocket.close()

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # Create a socket object
    host = socket.gethostname() # Get local machine name
    #port = 3001                 # Reserve a port for your service.
    port = int(input("Enter port: "))

    print ('Server started at [%s]' % socket.gethostbyname(host))
    print ('Waiting for clients...')

    #s.bind((host, port))       # Bind to the port
    s.bind(('0.0.0.0', port))
    s.listen(5)                 # Now wait for client connection.

    while True:
        #Waits until someone new to accept
        c, addr = s.accept()
        print(addr, "connected.")
        clients.append(c)
        thread_recv = Thread(target=recv, args=((c,)))
        thread_recv.start()

        thread_send = Thread(target=send, args=((c,)))
        thread_send.start()


    s.close()

Upvotes: 1

Related Questions