使用线程编程的套接字编程

时间:2016-04-08 13:16:08

标签: python multithreading sockets

这是我为V2V communication编写的通用代码。我的意图是,如果网络中有n个车辆,他们应该能够向其他(n-1)车辆发送消息并从他们那里接收。

import socket
import threading
ports = [30151,30152,30153]
class V2V_comm(threading.Thread):
     global ports
     def __init__(self,port):
     threading.Thread.__init__(self)
     self.host = "127.0.0.1"
     self.port = port
     self.skt = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
     self.skt.bind((self.host,self.port))
     self.log_info = []
     self.open_server = False
     print "Starting server with ports: ",self.port
     self.skt.settimeout(0.2)

def run(self):
     print "I m here"
     message = raw_input("Give a message >>")
     while message != "Q":
         try:
             for port in ports:
                 if self.port != port:
                     print "Sending present location and message"
                     self.skt.sendto(message,(self.host,port))
                     message = raw_input("Give a message >>")
          except:
             print "Something is going wrong"

 def receiving_data(self):
     #while True:
         try:
             print "Ready to receive data"
             data,addr = self.skt.recvfrom(1024)
             print "The points received are: ", str(data)
             print "The points are received at: ", self.port
             self.log_info.append(data)
             print self.log_info

         except:
             print "unable to receive"

V1 = V2V_comm(30151)
V2 = V2V_comm(30152)
V3 = V2V_comm(30153)

V1.start()
V2.start()
V3.start()

V1.receiving_data()
V2.receiving_data()
V3.receiving_data()

但它无法正常工作。有人可以提出任何改变吗?

0 个答案:

没有答案