Peter Mills
Peter Mills

Reputation: 11

s.sendall doesn't work inside a thread in python

I'm trying to develop a chat program in python. I want it to have multiple clients so I'm using threading to handle this. However when I try to send the message to all connected clients, the server only sends it to the client which sent the message. I'm not sure if I'm just missing something obvious but here is the code for the server:

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,))

And here is the code for the client:

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

Upvotes: 1

Views: 826

Answers (2)

3xt
3xt

Reputation: 66

You can try by pulling up the list of users, and iterating through it, and doing an individual send of the same message, though, unless you are the administrator and want to broadcast a warning, this functionality would be pretty mundane.

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182779

The "all" in sendall means that it sends all of the data you asked it to send. It doesn't mean it sends it on more than one connection. Such an interface would be totally impractical. For example, what would happen if another thread was in the middle of sending something else on one of the connections? What would happen if one of the connections had a full queue?

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

Upvotes: 3

Related Questions