我对网络和套接字编程完全陌生。我尝试了一些代码;假设我有 3 个客户端和一个服务器 c1 消息,它通过服务器并反映在 c2 和 c3 中。
我的问题:
- 我不想看到我自己的消息(如果我说“嗨”,它也会显示给我,但它应该只显示在 c2 和 c3 中)。
- 有没有一种方法,当 c1 发送消息时,只有 c2 可以看到消息而不是 c3
- 无法在 Python 中执行此操作并显示错误,那么如何在 Python 3 中完成
服务器.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 代码。
客户端.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 行消息“嗨”也显示给我。