python - 如何在Python中创建TCP服务器?

标签 python sockets networking

我开始学习使用python建立网络,有人无法帮助我解决这段代码,因为我一次无法连接5个以上的客户端。有人可以建议我解决这个问题吗?

def main():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.bind(('', listening_port))
        s.listen(5)
        print "[*] Initializing Sockets ... Done"
        print "[*] Sockets Binded Successfully ..."
        print("[*] Server Started Successfully [%d]\n" % (listening_port))
    except Exception, e:
        print e
        sys.exit(2)
    while 1:
        try:
            conn, addr = s.accept()
            data = conn.recv(buffer_size)
            start_new_thread(conn_string, (conn, data, addr))
        except KeyboardInterrupt:
            s.close()
            print "\n[*] Proxy Server Shutting Down ..."
            sys.exit(1)
    s.close()

def conn_string(conn, data, addr):
    print conn
    print addr
    print data

最佳答案

如python套接字API中所述:

socket.listen(backlog)

Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 0; the maximum value is system-dependent (usually 5), the minimum value is forced to 0.


将数量从5增加到希望与服务器建立的同时连接数。

关于python - 如何在Python中创建TCP服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47260056/

相关文章:

java - 尝试 ping 时,抛出 java.net.UnknownHostException。我不明白原因

linux - 使用 iptables 记录所有到关闭端口的连接

python - 如何在 Pandas 数据框中正确绘制条形图? x 值继续显示为索引

python - 为什么 defaultdict(int) 的 dicts 使用这么多内存? (以及其他简单的 python 性能问题)

c - 在 C 中保持套接字打开

php - 使用 PHP 套接字模块检测对等断开连接 (EOF)

ios - POSIX网络没有激活蜂窝 radio ?

python - 将 unicode 值(不带\u)映射到正确的解码字符串

python - 使用内联/嵌入式图在 IPython 中运行 python 脚本

c++ - Mac/IOS 是否使用与 Linux 内核相同的 sys/socket.h?