python服务端对应多个客户端_python tcp服务器将数据发送到多个客户端

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'));

});

解决方案

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)

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值