我对网络和套接字编程完全陌生。我试过一些代码;说我有3个客户端和一个服务器c1消息,它通过服务器并反映在c2和c3。
我的问题:
server.py
import socket
import time
host = ''
port = 5020
clients = []
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
a=s.bind((host, port))
#s.setblocking(0)
quitting = False
print "Server Started."
print("socket binded to %s" % (port))
while not quitting:
try:
data, addr = s.recvfrom(1024)
if "Quit" in str(data):
quitting = True
if addr not in clients:
clients.append(addr)
#print clients
for client in clients:
if not a:# tried this for broadcasting to others not c1
s.sendto(data, client)
print time.ctime(time.time()) + str(addr) + ": :" + str(data)
except:
pass
s.close()
这是Python 2代码。
client.py
enter code hereimport socket
import threading
import time
shutdown = False
def receving(name, sock):
while not shutdown:
try:
while True:
data, addr = sock.recvfrom(1024)
print str(data)
except:
pass
host = ''
port = 5020
server = ('',5020)
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind((host, port))
#s.setblocking(0)
for i in range(5):
threading.Thread(target=receving, args=("RecvThread",s)).start()
alias = raw_input("Name: ")
message = raw_input(alias + "-> ")
while message != 'q':
if message != '':
s.sendto(alias + ": " + message, server)
message = raw_input(alias + "-> ")
time.sleep(0.1)
shutdown = True
s.close()
输入到服务器的输出是正确的时间和服务器消息,但我的问题是客户端输出c1消息显示在c1本身。
Name: c1
c1-> hi
c1-> c1: hi
在第3行看到消息" hi"也向我展示。
答案 0 :(得分:0)
而不是
for client in clients:
if not a:# tried this for broadcasting to others not c1
s.sendto(data, client)
你可以这样做:
for client in clients:
if client!=addr:# tried this for broadcasting to others not c1
s.sendto(data, client)
因为当您执行此操作时,每个连接的客户端的地址都存储在 addr 变量中:
data, addr = s.recvfrom(1024)