SOCKET局域网数据传输

Posted Tequila Sunrise

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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:\\ProgramData\\Anaconda2\\python.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:\\ProgramData\\Anaconda2\\python.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.ang

以上是关于SOCKET局域网数据传输的主要内容,如果未能解决你的问题,请参考以下文章

C# Socket编程实现简单的局域网聊天器

Android 通过局域网udp广播自动建立socket连接

Java TCP Socket编程:客户端和服务器在同一台计算机上通信良好,但无法通过局域网相互发送数据

5-网络芯片CH395Q学习开发-模块使用Socket0作为TCP客户端和电脑上位机TCP服务器局域网通信

团队项目

你好,博客园!!第一弹~局域网下的简易聊天室,socket与多线程简结