1
我在嘗試向我的python tcp聊天服務器上連接的所有客戶端發送數據時遇到問題。我知道如何讓消息/數據直接發送給發送它的人,但如果我有多個客戶端,它將不會發回。這是迄今爲止我的服務器: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'));
});
有你發送代碼中的錯誤,你沒有注意到。你忘了檢查'send'的返回值。閱讀該方法的文檔,瞭解爲什麼這是必要的。您還使用阻塞套接字,這意味着您的服務器只能像最慢的客戶端可以處理數據一樣快速地處理數據。你可能想看看http://twistedmatrix.com/,以獲得一種更簡單的Python網絡編程方法(就像Python的Node.js!) –