• SOCKET局域网数据传输


    Author : LEON
    EMAIL:yangli0534@yahoo.com 程序的主要功能

    发送端:做为server,将指定协议的数据骑过socket发送出去。
    接收端: 1.SOCKET接收数据 2.解析指令帖并得到命令参数 3.根据命令参数更新GUI 其中1和2在一个线程,3在一个线程

    捕获

    捕获2

    捕获3

    发送数据代码:

      1 ##-*- coding: utf-8-*
      2 #!D:ProgramDataAnaconda2python.exe
      3 
      4 import sys
      5 import math
      6 import time
      7 #import serial
      8 from PyQt5 import QtCore, QtGui, uic, QtPrintSupport, QtWidgets
      9 #import serial.tools.list_ports
     10 from  threading import Thread
     11 from PyQt5.QtCore import *
     12 from PyQt5.QtGui import *
     13 from PyQt5.QtWidgets import *
     14 import random
     15 import socket
     16 
     17 qtCreatorFile = "paneltest.ui"
     18 Ui_MainWindow, QtBaseClass=uic.loadUiType(qtCreatorFile)
     19 
     20 
     21 class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
     22     #i = 0
     23     #start = False
     24     def __init__(self):
     25         QtWidgets.QMainWindow.__init__(self)
     26         Ui_MainWindow.__init__(self)
     27         # bkg = QtGui.QPalette()
     28 
     29         # bkg.setColor(self.backgroundRole(),QColor(192,253,123))
     30         # self.setPalette(bkg)
     31         self.setupUi(self)
     32         #self.ser =serial.Serial()
     33         #port_list = list(serial.tools.list_ports.comports())#find serial port avaliable
     34         #NoSerial = len(port_list)
     35         #if  NoSerial> 0:
     36         #    for port in port_list:
     37         #        self.comboBox_serial_No.addItem(port[0])#add to comboBox
     38         #baudrate = [9600,14400, 19200, 38400, 56000, 57600, 115200]
     39         #for baud in baudrate:
     40         #    self.comboBox_serial_baudrate.addItem(str(baud))
     41         #self.comboBox_serial_baudrate.setCurrentIndex(len(baudrate)-1)
     42         #self.comboBox_serial_No.setCurrentIndex(NoSerial-1)
     43         #self.pushButton_open.clicked.connect(self.open)    
     44         #self.pushButton_send.clicked.connect(self.ctrl)
     45         TCP_IP = '127.0.0.1'
     46         TCP_PORT = 5005
     47         BUFFER_SIZE = 20  # Normally 1024, but we want fast response
     48         self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     49         self.s.bind((TCP_IP, TCP_PORT))
     50         self.s.listen(1)
     51         Thread(target=self.connect,args=()).start()     
     52         #con = threading.Condition()
     53         #rece=threading.Thread(target=self.receive,args=())
     54         #rece.start()
     55         #Thread(target=self.receive).start()
     56     def closeEvent(self):
     57         #QtWidgets.QMainWindow.__close_(self)
     58         #Ui_MainWindow.__close__(self)
     59         self.conn.close()
     60         self.t.close()
     61         self.s.close()
     62         #self.close()
     63     def connect(self):
     64         #port = self.comboBox_serial_No.currentText()
     65         #baudrate = int(self.comboBox_serial_baudrate.currentText())
     66         self.conn, self.addr = self.s.accept()
     67         while not self.conn:
     68             self.conn, self.addr = self.s.accept()
     69         #if self.ser.isOpen():
     70             #self.label_tip.setText('this port has been opened')
     71             #self.ser.close()
     72         self.label.setText("Connted")
     73         self.t = Thread(target=self.autosend)
     74         self.t.setDaemon(True)
     75         self.t.start()
     76         #self.label_tip.setText('closed')
     77         #else:
     78             #self.ser = serial.Serial(port, baudrate, timeout = 10)
     79             #if self.ser.isOpen():
     80             #    self.pushButton_open.setText('Connected')
     81             #    self.label_tip.setText("open sucessed!")
     82                 #self.ser.write('roger!')
     83             #else:
     84     def open(self):
     85         #port = self.comboBox_serial_No.currentText()
     86         #baudrate = int(self.comboBox_serial_baudrate.currentText())
     87         self.conn, self.addr = self.s.accept()
     88         #if self.ser.isOpen():
     89             #self.label_tip.setText('this port has been opened')
     90             #self.ser.close()
     91         self.label.setText("Connted")
     92         self.t = Thread(target=self.autosend)
     93         self.t.setDaemon(True)
     94         self.t.start()
     95         #self.label_tip.setText('closed')
     96         #else:
     97             #self.ser = serial.Serial(port, baudrate, timeout = 10)
     98             #if self.ser.isOpen():
     99             #    self.pushButton_open.setText('Connected')
    100             #    self.label_tip.setText("open sucessed!")
    101                 #self.ser.write('roger!')
    102             #else:
    103             #    self.label_tip.setText('open failed!')        
    104     def ctrl(self):    
    105         #if self.ser.isOpen():
    106         #if (print 'self.conn' in dir()) and (print 'self.t' in dir()):
    107         if True:
    108             if not self.t.is_alive():
    109             #text = self.lineEdit_sendBuffer.text()
    110                 #self.pushButton_send.setText('stop')
    111                 #self.start = False
    112                 #self.t.wait()
    113                 #self.t.quit()
    114             #else:
    115                 self.pushButton_send.setText('send')
    116                 self.start = True
    117                 self.t.start()
    118     
    119     def autosend(self):
    120         frame = [int('7e',16),int('7e',16),0,0,0,0,0,0,0,int('8e',16),int('8e',16)]
    121         self.pushButton_send.setText('sending')
    122         self.i = 0
    123         j = 0
    124         data =''
    125         while True:
    126             frame[2] = j
    127             if self.i % 10 ==0:
    128                 frame[3] =int(random.random()*39)            
    129                     frame[4] =int(random.random()*255)
    130                     frame[5] =int(random.random()*39)            
    131                     frame[6] =int(random.random()*255)
    132             frame[7] = self.i /256
    133             frame[8] = self.i % 256
    134             data =''
    135                 for tmp in frame:
    136                     data= data + ' '+ str(int(tmp))
    137                 #print(data)
    138                 self.conn.send(data)  # echo    
    139                 time.sleep(0.2)
    140             #self.pushButton_send.setText(str(j))
    141             #self.label_tip.setText(data)
    142                 if self.i < 18000:
    143                         self.i += 11
    144                     else:
    145                         self.i = 0
    146                        if j < 255:
    147                             j+=1
    148                             #    #self.pushButton_send.setText('sending'+str(j))
    149                             #    #self.label_tip.setText('frame='+data)
    150                     else:
    151                             j = 0
    152 
    153 if __name__ == "__main__":
    154     app = QtWidgets.QApplication(sys.argv)
    155     w = MyApp()
    156     w.show()
    157     sys.exit(app.exec_())
    158     

    接收数据代码

      1 ##-*- coding: utf-8-*
      2 #!D:ProgramDataAnaconda2python.exe
      3 """
      4 Author : LEON
      5 EMAIL:yangli0534@yahoo.com
      6 程序的主要功能
      7 1.SOCKET接收数据
      8 2.解析指令帖并得到命令参数
      9 3。根据命令参数更新GUI
     10 其中1和2在一个线程,3在一个线程
     11 """
     12 import sys
     13 import math
     14 import time
     15 #import serial
     16 from PyQt5 import QtCore, QtGui, uic, QtPrintSupport, QtWidgets
     17 #import serial.tools.list_ports
     18 from  threading import Thread
     19 from PyQt5.QtCore import *
     20 from PyQt5.QtGui import *
     21 from PyQt5.QtWidgets import *
     22 import socket 
     23 
     24 qtCreatorFile = "panel.ui"# GUI file
     25 Ui_MainWindow, QtBaseClass=uic.loadUiType(qtCreatorFile)
     26 
     27 class MyApp(QtWidgets.QMainWindow, Ui_MainWindow):
     28     angle = pyqtSignal(dict) # thread signal 
     29     
     30     def __init__(self):
     31          
     32         QtWidgets.QMainWindow.__init__(self)
     33         Ui_MainWindow.__init__(self)
     34         QThread.__init__(self)
     35         # bkg = QtGui.QPalette()
     36         # bkg.setColor(self.backgroundRole(),QColor(192,253,123))
     37         # self.setPalette(bkg)
     38         self.setupUi(self)
     39         #self.ser =serial.Serial()#serial port handle
     40         #port_list = list(serial.tools.list_ports.comports())#find serial port avaliable
     41         #NoSerial = len(port_list)#number of avaliable serial port 
     42         #if  NoSerial> 0:
     43         #    for port in port_list:
     44         #        self.comboBox_serial_No.addItem(port[0])#add to comboBox
     45         #baudrate = [9600,14400, 19200, 38400, 56000, 57600, 115200]#baudrate
     46         #for baud in baudrate:
     47         #    self.comboBox_serial_baudrate.addItem(str(baud))
     48         #self.comboBox_serial_baudrate.setCurrentIndex(len(baudrate)-1)#default baudrate
     49         #self.comboBox_serial_No.setCurrentIndex(NoSerial-1)#default port
     50         #self.pushButton_open.clicked.connect(self.open)    #serial port open event connted to button clicked
     51         
     52         #self.pushButton_send.clicked.connect(self.send)    #send data event
     53         #self.lcdNumber.display(ord('a'))
     54         #self.param = {"p1":0,"p2":0,"p3":0}
     55         TCP_IP = '127.0.0.1'
     56         TCP_PORT = 5005
     57         BUFFER_SIZE = 1024
     58         self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
     59         self.s.connect((TCP_IP, TCP_PORT))
     60         self.para1 = 0 # cmd initialization
     61         self.para2 = 0
     62         self.para3 = 0
     63         self.para4 = 0
     64         self.para5 = 0
     65         self.para6 = 0
     66         #self.angle.connect(self.lcdNumber.display)
     67         self.angle.connect(self.paraP)
     68         #self.angle.connect(self.label_3.setText)
     69         self.sec = 0
     70         #self.dial.setValue(90)
     71         #self.label_tip_2.valueChanged.connect(self.dial.setValue())
     72         #self.dial.setFocusPolicy(Qt.StrongFocus)
     73         #self.angle.connect(self.dial.setValue)
     74         #self.dial.valueChanged.connect(self.slider.setValue)
     75         #con = threading.Condition()
     76         #rece=threading.Thread(target=self.receive,args=())
     77         #rece.start()
     78         self.threads =[]
     79         t1 = Thread(target=self.receive)
     80         t1.setDaemon(True) #
     81         t1.start()#start receiving data thread
     82         self.threads.append(t1) 
     83         t2 =Thread(target=self.updateP) 
     84         t2.setDaemon(True)
     85         t2.start() # start update GUI thread
     86         self.threads.append(t2) 
     87         #self.updateP()
     88         '''            
     89     def open(self):#open serial port
     90         port = self.comboBox_serial_No.currentText()
     91         baudrate = int(self.comboBox_serial_baudrate.currentText())
     92         if not self.ser.isOpen():
     93             #self.label_tip.setText('this port has been opened')
     94             #self.ser.close()
     95             #self.pushButton_open.setText('已断开')
     96             #self.label_tip.setText('closed')
     97         #else:
     98             self.ser = serial.Serial(port, baudrate, timeout = 10)
     99             if self.ser.isOpen():
    100                 self.pushButton_open.setText('已连接')
    101                 self.label_tip.setText('open sucessed!')
    102                 self.ser.write('roger!')
    103             else:
    104                 self.label_tip.setText('open failed!')        
    105     '''
    106     #def send(self):    #send data
    107         #if self.ser.isOpen():
    108         #    text = self.lineEdit_sendBuffer.text()
    109         #    self.ser.write(str(text))
    110     def receive(self):# receive data from uart and analysis the protocol frame to get the parameter 
    111         #, and then emit to main thread
    112         #self.sec += 1
    113         #self.lcdNumber.display(self.sec)
    114         fsm = 0
    115         cnt_last = 0
    116         cnt_new = 1 
    117         first = True
    118         info = {"p1":0,"p2":0,"p3":0,"p4":0,"p5":0,"p6":0}
    119         while True:
    120             data = self.s.recv(100)
    121             print data
    122                 data = data.split(' ')
    123                 if len(data)==12:
    124                     for i in range(1,len(data)):
    125                             data[i] = int(data[i])
    126                 cnt_last = cnt_new
    127                 cnt_new = data[3]
    128                 if not ((cnt_new - cnt_last == 1) or (cnt_new ==0 and cnt_last ==255) or first == True):
    129                     print "frame lost, this is ",cnt_new, ' frame'
    130                 first = False
    131                         if data[1] == int('7E',16) and data[11] == int('8E',16) :
    132                             info["p1"] = data[4]
    133                             info["p2"] = data[5]
    134                             info["p3"] = data[6]
    135                             info["p4"] = data[7]
    136                             info["p5"] = data[8]
    137                             info["p6"] = data[9]
    138                             self.angle.emit(dict(info))#emit signal to main programe
    139                 else:
    140                     print "frame format error"
    141             else:
    142                 print "frame length error"
    143             '''
    144              if self.ser.isOpen():
    145                  try:
    146                     text = self.ser.read(1) #read one byte from uart
    147                     if not text :
    148                          break
    149                     else:
    150                         #self.label_3.setText(str(fsm))
    151                         text = ord(text)
    152                         if fsm == 0:#frame analysis FSM
    153                             if text ==int('7e',16):
    154                                 fsm = 1
    155                             else:
    156                                 fsm = 0
    157                         elif fsm == 1:
    158                             info = {"p1":0,"p2":0,"p3":0,"p4":0,"p5":0,"p6":0}
    159                             if text ==int('7e',16):
    160                                 fsm = 2
    161                             else:
    162                                 fsm = 0
    163                         elif fsm == 2:
    164                             info["p1"]=text
    165                             fsm = 3
    166                         elif fsm == 3:
    167                             info["p2"]=text
    168                             fsm = 4
    169                         elif fsm == 4:
    170                             info["p3"]=text
    171                             fsm = 5    
    172                         elif fsm == 5:
    173                             info["p4"]=text
    174                             fsm = 6
    175                         elif fsm == 6:
    176                             info["p5"]=text
    177                             fsm = 7
    178                         elif fsm == 7:
    179                             info["p6"]=text
    180                             fsm = 8        
    181                         elif fsm == 8:
    182                             if text ==int('8e',16):
    183                                 fsm = 9
    184                             elif text ==int('7e',16):
    185                                 fsm = 1
    186                             else:
    187                                 fsm = 0
    188                         elif fsm ==9:
    189                             if text ==int('8e',16):
    190                                 fsm = 0
    191                                 self.angle.emit(dict(info))#emit signal to main programe
    192                             elif text ==int('7e',16):
    193                                 fsm = 1
    194                             else:
    195                                 fsm = 0
    196                          #self.angle.emit(str(text))
    197                          #self.dial.setValue(int(text))
    198                          #self.angle.emit(str((text)))
    199                          
    200                          #self.angle1.emit(int(text))
    201                  except:
    202                      break
    203             '''
    204             #if self.ser.isOpen():
    205              # try:
    206                 # text = self.ser.read(1) 
    207                 # if not text :
    208                      # break
    209                 # else:
    210                     # self.angle.emit(str(ord(text)))
    211                     # #self.dial.setValue(int(text))
    212                     # #self.angle.emit(str((text)))
    213                     
    214                     # #self.angle1.emit(int(text))
    215              # except:
    216                  # break
    217     def paraP(self,r_dict):#update GUI
    218         self.para1 = r_dict["p1"]*256+r_dict["p2"]
    219         self.para2 = r_dict["p3"]*256+r_dict["p4"]
    220         self.para3 = r_dict["p5"]*256+r_dict["p6"]
    221         #self.para4 = r_dict["p4"]
    222         #self.para5 = r_dict["p5"]
    223         #self.para6 = r_dict["p6"]
    224     def updateP(self):
    225         #self.sec += 1
    226         #self.lcdNumber.display(self.sec)
    227         while True:
    228             # if self.sec < 180:
    229                 # self.sec += 1
    230             # else:
    231                 # self.sec = 0
    232             #time.sleep(0.5)
    233             #print("Thread update--sec="),
    234             #print(self.sec),
    235             #print("tmp="),
    236             time.sleep(1.0/10.00)
    237             tmp =str(1.0*self.para1/100.0)
    238             self.lcdNumber_2.display(tmp)
    239             tmp =str(1.0*self.para2/100.0)
    240             self.lcdNumber_3.display(tmp)
    241             tmp =str(1.00*self.para3/100.00)
    242             self.lcdNumber.display(tmp)
    243             #print(tmp)
    244             #self.label_tip_3.setText(tmp)
    245             #print(len(tmp))
    246             #if len(tmp) <4:
    247             tmp = int(str(self.para3),10)
    248                 #print("Number = "),
    249                 #print(tmp)
    250                 #self.label_3.setText(str(tmp))
    251                 #if tmp > 0 and tmp < 180:
    252             #self.dial.setValue(tmp)
    253                     
    254                     
    255 if __name__ == "__main__":
    256     app = QtWidgets.QApplication(sys.argv)
    257     w = MyApp()
    258     w.show()
    259     #for t in w.threads:
    260         #t.setDaemon(True)
    261         #t.start()
    262     #w.updateP()    
    263     # while True:
    264         # time.sleep(0.1)
    265         # tmp =str(w.label_tip_2.text())
    266         # if tmp.isdigit():
    267             # tmp = int(tmp,10)
    268             # if tmp > 0 and tmp < 180 :
    269                  # w.dial.setValue(tmp)
    270 #                self.lcdNumber.display(tmp)
    271     sys.exit(app.exec_())
    272     
  • 相关阅读:
    Linux makefile 教程 非常详细,且易懂
    PCRE函数简介和使用示例
    Eclipse常用快捷键汇总
    vc6.0 调用ocx控件
    理解串口流控
    c++ xml markup
    unresolved external symbol __endthreadex错误解决(
    Android自动化~1
    数据库左连接,右连接,内连接,外连接
    Linux常用指令
  • 原文地址:https://www.cnblogs.com/hiramlee0534/p/7163688.html
Copyright © 2020-2023  润新知