如何使用线程进行UDP多聊天服务器套接字程序?

时间:2017-04-01 11:49:44

标签: multithreading udp python-sockets

我对网络和套接字编程完全陌生。我试过一些代码;说我有3个客户端和一个服务器c1消息,它通过服务器并反映在c2和c3。

我的问题:

  1. 我不想看到自己的信息(如果我说"嗨"它也会显示给我,但它应该只显示在c2和c3中)。
  2. 有一种方式,只有c2可以看到一条消息而不是c3,当c1发送它时
  3. 无法在Python中执行此操作并显示错误,因此如何在Python 3中完成
  4. 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"也向我展示。

1 个答案:

答案 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)