Python Socket - >同时发送/接收消息

时间:2018-06-07 00:34:00

标签: python python-3.x

基本上我一直在使用套接字和线程处理一个简单的项目。 我的问题是我有很多线程,我想让一个线程向另一个线程发送消息,同时线程从客户端收到很多消息,我是怎么做的,谢谢。 这是我的客户端和服务器的功能

     def client(self,addr, port,msg):
            print("capteur with addr ", self.addr, "connecting to :", addr)

            conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            conn.bind((self.addr, self.port))
            conn.connect((addr, port))

            conn.send(str.encode(str(msg)))

            '''data = conn.recv(2048)
            print('data received from server', addr, ':',data.decode('utf-8'))'''
            conn.close()
#methode serveur 
    def server(self):

            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                s.bind((self.addr, self.port))
            except socket.error as e:
                print(str(e))
            s.listen(len(self.listvoisin_cellule))
            print('Capteur',self.addr, 'of port',self.port,'Waiting for a connection.\n')
            while True:

                try:
                    conn, ad = s.accept()
                except socket.timeout as e:
                    print(str(e))
                    s.close()
                    return

                print('client : '+ad[0]+':'+str(ad[1]),' connected')
                data = conn.recv(2048)
                print('data received from client', ad[0],':', ad[1],' is :', data.decode('utf-8'))

                strData= data.decode('utf-8')
                infos= strData.split(',')
                a=float(infos[0])
                self.listdistance.append(a)
                conn.close()
            s.close()

0 个答案:

没有答案