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

标签 python multithreading sockets

我正在尝试用 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/

相关文章:

python - numpy 不同长度数组的平均值/标准差

java - 如何从外部不相关的代码读取正在运行的 Swing GUI 的 TextField 或 Cell 值?

java - 通过 TCP 套接字发送对象 - ClassNotFoundException

Java TCP Socket 接收指定长度的字节

python - Swift NSSocket 编程/python 教程修复

python - skimage 将 RGB 转换为 HSV 时如何获得正确的颜色。了解色调

java - XBee 系列 2 尝试接收数据包时挂起并超时

python - BeautifulSoup 返回空的 span 元素?

multithreading - PowerShell 和单线程单元

c# - 如何在不阻塞 UI 的情况下顺序运行多个任务?