gpt4 book ai didi

python - s.sendall 不能在 python 的线程内工作

转载 作者:行者123 更新时间:2023-11-30 23:10:59 25 4
gpt4 key购买 nike

我正在尝试用 python 开发一个聊天程序。我希望它有多个客户端,所以我使用线程来处理这个问题。但是,当我尝试将消息发送到所有连接的客户端时,服务器仅将其发送到发送消息的客户端。我不确定我是否遗漏了一些明显的东西,但这是服务器的代码:

import socket
from thread import *

host = '192.168.0.13'
port = 1024
users = int(input("enter number of users: "))

def clienthandler(conn):
while True:
data = conn.recv(1024)
if not data:
break
print data
conn.sendall(data)
conn.close()


serversock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversock.bind((host, port))
serversock.listen(users)

for i in range(users):
conn, addr= serversock.accept()
print 'Connected by', addr
start_new_thread(clienthandler, (conn,))

这是客户端的代码:

import socket

host = '192.168.0.13'
port = 1024

usrname = raw_input("enter a username: ")
usrname = usrname + ": "
clientsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
clientsock.connect((host, port))

while True:
x = raw_input('You: ')
x = usrname + x
clientsock.sendall(x)
data = clientsock.recv(1024)
print data

最佳答案

sendall 中的“all”表示它发送您要求发送的所有数据。这并不意味着它会在多个连接上发送它。这样的接口(interface)是完全不切实际的。例如,如果另一个线程正在其中一个连接上发送其他内容,会发生什么情况?如果其中一个连接的队列已满,会发生什么情况?

sendall: Send data to the socket. The socket must be connected to a remote socket. The optional flags argument has the same meaning as for recv() above. Unlike send(), this method continues to send data from string until either all data has been sent or an error occurs. None is returned on success. On error, an exception is raised, and there is no way to determine how much data, if any, was successfully sent. -- 17.2. socket

关于python - s.sendall 不能在 python 的线程内工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30404589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com