【问题标题】:Python 3 socket client not connecting to serverPython 3套接字客户端未连接到服务器
【发布时间】:2019-01-08 18:42:48
【问题描述】:

我有一个 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。即使我已经关闭计算机并再次尝试。但是当我去谷歌问我的IP地址是什么时,情况就完全不同了。为什么socket一直选择192.168.56.1?它有什么特别之处吗?这与我的问题有关吗?

【问题讨论】:

  • 尝试在s.bind(('0.0.0.0', port)中做server.py

标签: python-3.x multithreading sockets


【解决方案1】:

只需将您的服务器绑定到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()

【讨论】:

  • 绑定到所有网络接口是什么意思?
  • 绑定到所有接口意味着您的套接字正在侦听的端口可以从您连接的所有网络访问
  • @Joe 哈哈!我告诉过你...用s.bind(('0.0.0.0', port)) 替换s.bind((socket.gethostbyname(host), port)) 。顺便说一句,如果之后无法建立连接,请尝试禁用防火墙
猜你喜欢
  • 2017-02-25
  • 1970-01-01
  • 2016-12-09
  • 1970-01-01
  • 1970-01-01
  • 2014-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多