Python套接字等待客户端连接

2024-10-01 07:45:08 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法在客户端连接到此服务器之前停止while循环? 服务器应该为每个新的客户端连接创建一个新线程,有可能吗?在

import socket
import threading

def clientdialog(myS):
    conn, addr = myS.accept()
    print ("Connection from: " + str(addr))

    while 1:
                data = conn.recv(1024).decode("utf-8")
                if not data or data == 'q':
                    break
                print ("from connected  user: " + str(data))

host = "192.168.1.3"
port = 1998

mySocket = socket.socket()
mySocket.bind((host,port))

while True:

    mySocket.listen(10)
    #whait until socket don't connect

    try:
        threading._start_new_thread(clientdialog, (mySocket))
    except:
        print("error starting thread")

Tags: fromimport服务器客户端datasocketconnaddr
1条回答
网友
1楼 · 发布于 2024-10-01 07:45:08

{1>被称为连接队列,因为它被称为cd1}函数。在

另一个名为socket.accept的函数将阻塞,直到建立连接。按如下方式修改代码:

mySocket = socket.socket()
mySocket.bind((host,port))
mySocket.listen(10)

while True:
    client_socket, client_address = mySocket.accept() # blocking call
    .... # do something with the connection

有关详细信息,请访问docs。在

此外,还需要将客户端套接字的详细信息传递给线程。不需要服务器套接字。实际上,是这样的:

^{pr2}$

在主循环中接受连接,然后将客户端详细信息传递给线程进行处理。在

相关问题 更多 >