Question

i am having trouble trying to send data to all clients connected on my python tcp chat server. i know how to get the message/data to send right back to the person who sent it but it just won't send back if i have multiple clients. this is my server so far:

host = '127.0.0.1'
port = 4446
backlog = 5
size = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind( (host, port) )
s.listen(backlog)
clients = [s]

while 1:
  inputReady, outputReady, exceptReady = select.select(clients, [], [])
  for x in inputReady: 

    if x == s: 
        csock, addr = s.accept() 
        clients.append(csock) 

    else:  
        data = x.recv(size) 
        if data: 
            for i in clients: #problem i believe is in here but i
                i.send(data)  #dont know how to fix it
        else: 
            x.close() 
            clients.remove(x) 
s.close()

i am using node.js for the client side and its very simple so far and i dont think its the problem:

var net = require('net');
var readline = require('readline');

var host = process.argv[2];
var port = process.argv[3];
var username = process.argv[4];
var client = new net.Socket();

client.connect(port, host, function(){
    var type = "connect";
    var sender = username;
    var msg = "has connected";
    var s = type + ':' + sender + ':' + msg;
    var length = s.length;
    client.write(length + " " + s);
});

client.on('data', function(data){
    console.log(data.toString('UTF-8'));
});
Was it helpful?

Solution

The problem is that you are sending on all sockets, including the server socket (s). Ignoring other potential problems, you can do a quick fix by doing this:

       for i in clients:
          if i is not s:
            i.send(data)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top