python-3.x - 为什么不能将多个客户端同时连接到服务器? Python

标签 python-3.x sockets

因此,可以说我有一个server.py和client.py,其中包含以下代码:

server.py

import socket

def listen():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "127.0.0.1"
    port = 5555

    s.bind((host, port))
    s.listen(128)

    print("LISTENING FOR INCOMING CONNECTIONS")

    c, addr = s.accept()
    print("GOT CONNECTION FROM", addr)

    while True:
        data = c.recv(1024)
        data = data.decode("utf-8")
        data = data.upper()
        c.send(data.encode("utf-8"))
listen()

和client.py
import socket

def connect():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "127.0.0.1"
    port = 5555

    s.connect((host, port))

    print("CONNECTED TO HOST")

    while True:
        command = input("command> ")
        s.send(command.encode("utf-8"))
        data = s.recv(1024)
        print(str(data.decode("utf-8")))
connect()

现在,如果我断开客户端连接并尝试重新连接到服务器,它将无法正常工作。 (由于无法正常工作,我的意思是无法建立连接)

最佳答案

listenserver.py函数中,您只调用一次accept函数。必须为要接受的每个客户端连接调用accept。要解决您的问题,您可以将函数的后半部分放入循环中:

def listen():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    host = "127.0.0.1"
    port = 5555

    s.bind((host, port))
    s.listen(128)

    while True:
        print("Waiting for an incoming connection...")
        c, addr = s.accept()
        print("GOT CONNECTION FROM", addr)

        # Serve the connection
        try:
            while True:
                data = c.recv(1024)
                if len(data) == 0:
                    print("Client closed connection")
                    break
                data = data.decode("utf-8")
                data = data.upper()
                c.send(data.encode("utf-8"))
        except Exception as e:
            print("Connection died: {}".format(e))

这意味着一次只能连接1个客户端。

我强烈建议不要看Python标准库中的SocketServer,而不是自己编写这种类型的代码。该库负责样板监听/接受工作,还具有一些高级功能,可让您轻松地同时处理多个客户端连接(如果需要)

https://docs.python.org/3/library/socketserver.html#socketserver-tcpserver-example

关于python-3.x - 为什么不能将多个客户端同时连接到服务器? Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55150257/

相关文章:

python-3.x - Pandas groupby 类型错误 : '>' not supported between instances of 'SeriesGroupBy' and 'int'

python - 我的 Kivy 程序在左下角出现一个随机的白色方 block

android - 通过热点获取连接设备的名称

java - 套接字 - SocketException : Socket Closed - Java

python - 如何在 pandas.DataFrame 中添加表情符号

python - 对于要在虚拟环境和非虚拟环境中运行的 Python 3 脚本,应使用什么 shebang?

python - 了解 Python 3 中的 XML 和 XSD 解析

python - python3-cd在反向shell中不起作用

java - 如何在套接字 channel 中发送和接收序列化对象

c# - C#TcpSockets是否以干净/正确的方式断开连接?