Python 3套接字客户端未连接到服务器

时间:2019-01-08 18:42:48

标签: python-3.x multithreading sockets

我有一个server.py和client.py对。当我在机器上运行服务器并打开多个终端以运行客户端时,我可以正常连接。但是,当我尝试在另一台计算机上运行客户端时,客户端永远不会连接到服务器。我敢肯定,几个月前我在多台计算机上测试了此代码,并且运行良好(尽管可能我记错了),但是我认为我更新了python版本,所以也许这就是为什么?我该如何在下面更改我的代码才能正常工作?

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

修改 每次启动服务器时,都会说我的IP地址是相同的:192.168.56.1。即使我已关闭计算机并再次尝试。但是当我去Google询问我的IP地址是什么时,那是完全不同的。为什么套接字继续选择192.168.56.1?有什么特别的吗?这与我的问题有关吗?

1 个答案:

答案 0 :(得分:0)

只需将您的服务器绑定到0.0.0.0将其绑定到所有网络接口

server.py

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

然后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(('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()