python tcp服务器向多个客户端发送数据

时间:2014-02-11 00:21:18

标签: python networking tcp network-programming tcpserver

我无法尝试将数据发送到我的python tcp聊天服务器上连接的所有客户端。我知道如何将消息/数据发送回发送给它的人,但如果我有多个客户端,它就不会发回。到目前为止这是我的服务器:

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

我使用node.js作为客户端,到目前为止非常简单,我不认为它的问题:

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 个答案:

答案 0 :(得分:2)

问题是您正在发送所有套接字,包括服务器套接字。忽略其他潜在问题,您可以通过这样做快速解决问题:

       for i in clients:
          if i is not s:
            i.send(data)