1

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'));
});
1
  • There's a bug in your sending code that you didn't notice. You forgot to check the return value of send. Read the documentation for that method to learn why this is necessary. You're also using blocking sockets which means your server can only process data as fast as the slowest client can process it. You may want to take a look at twistedmatrix.com for an easier approach to network programming in Python (it's like Node.js for Python!) Commented Feb 11, 2014 at 13:17

1 Answer 1

2

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.