pythonUDP transmission structure, aligned to the C ++ structure

Give the program first:

import random
import socket
import struct
import threading
import pickle
import json
from struct import *
from time import sleep


class sendMsg:
    def __init__(self):
        self.sendType=b'\x01'#ready
        self.cliType=b'\x01'
        self.lonDir=b'E'
        self.latDir=b'N'
        self.cliNum=1
        self.lonDeg=100
        self.lonMin=100
        self.lonSec=100
        self.latDeg=100
        self.latMin=100
        self.latSec=100
        self.year=2019
        self.month=9
        self.day=6
        self.hour=12
        self.minute=10
        self.second=10
        self.ipFirst=192
        self.ipSecond=168
        self.ipThird=6
        self.ipFourth=108
        self.typeStr='cccciiiiiiiiiiiiiiiii'

    def __str__(self):
        return self.cliNum
class RecMsg():
    def __init__(self):
        self.id=b'\x02'
        self.ipFirst=192
        self.ipSecond=168
        self.ipThird=6
        self.ipFourth=108
        self.port=-1
        self.errorType=b'\x01'
        self.bandWidth=-1
        self.typeStr='=ciiiiici'


class CommunateThread(threading.Thread):  # 继承父类threading.Thread
    def __init__(self, id,packetLoss,socket,localIP,localPort,remoteIP,remotePort,file):
        threading.Thread.__init__(self)
        self.id=id
        self.packetLoss=packetLoss
        self.socket=socket
        self.localIP = localIP
        self.localPort=localPort
        self.remoteIP = remoteIP
        self.remotePort =remotePort 
        self.file = File
     DEF run (Self):   # to write the code to be executed inside the thread will run run run function function directly after the creation 
        Connect = False
         the while True:
             IF  not Connect: 
                self.sendConnect () 
            Data, addr = self.socket.recvfrom (1024 )
             Print ( " receiving the transmitted message {} {} " .format (addr, Data)) 
            recMes = RecMsg () 
            recData = struct.unpack (recMes.typeStr, Data)
             print (recData )
            if recData[0]==b'\x01' or (recData[0]==b'\x03' and recData[6]==b'\x01'):
                self.sendFile(recData)
    def readFile(self):
        with open(self.file,"rb") as f:
            data = f.read(1024)
            while data:
                yield data
                data=f.read(1024)
    def sendFile(self,recData):
        ip = "{}.{}.{}.{}".format(recData[1],recData[2],recData[3],recData[4])
        port = recData[5]
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            i =1
            for data in self.readFile():
                p = random.randint(1,100)
                if p<self.packetLoss:
                    continue
                s.sendto(data,(ip,port))
                sleep(0.005)
                i+=1
                if i%1000:
                    print(i," : send to {}:{},1k".format(ip,port))

            print("发送完成,总计发送 {} K".format(i))
        except Exception as e:
            print(e)
    def sendConnect(self):
        connect =sendMsg()
        connect.cliNum=self.id
        data=pack(  connect.typeStr,
                    connect.sendType,
                    connect.cliType,
                    connect.lonDir,
                    connect.latDir,
                    connect.cliNum,
                    connect.lonDeg,
                    connect.lonMin,
                    connect.lonSec,
                    connect.latDeg,
                    connect.latMin,
                    connect.latSec,
                    connect.year,
                    connect.month,
                    connect.day,
                    connect.hour,
                    connect.minute,
                    connect.second,
                    connect.ipFirst,
                    connect.ipSecond,
                    connect.ipThird,
                    connect.ipFourth)
        #data=pack('ccccb',connect.sendType,connect.cliType,connect.lonDir,connect.lonDir,connect.year)
        print(data)
        self.socket.sendto(data,(self.remoteIP,self.remotePort))
        print("send to {}:{}\t\n{}".format(self.remoteIP,self.remotePort,connect.__str__()))
def print_time(threadName, delay, counter):
    pass
View Code

Eager to send out the message, so the code a bit chaotic, there is no comment, hee hee.

We know python use UDP to send messages can only be sent byte out. How, then, and a c ++ (c #) body structure packing and unpacking it? Using the pack and unpack it.

For example, our structure is such that

 

 They are char and int type data. So we put this structure (being that it is a structure) packed into a byte stream:

 

 Me packing, sent directly, a number of bytes (characters / char) * 4 + 4 (int) * 17 = 32 bits. With c ++ / c # reception, no problem.

But the reception, the problem can not be aligned. So our definition of unpack format received:

 

 As for why add a "=", can be found python documentation, a detailed explanation.

Chinese version: https://docs.python.org/zh-cn/3.6/library/struct.html

English version: Https://Docs.Python.Org/3.6/Library/struct.Html

Guess you like

Origin www.cnblogs.com/superxuezhazha/p/11497895.html