套接字的Python C#数据类型

套接字的Python C#数据类型

问题描述:

我正在创建一个套接字服务器,以通过TCP连接C#程序并与之交谈.当前,我正在尝试创建一种将通过TCP套接字发送的十六进制转换为特定变量的方法(变量类型将在数据包头中,是的,我确实知道tcp是一种从技术上讲不是在发送数据包的流,但是我正在设计它这).目前,我已经通过下面的代码正确地将所有C#整数数值类型与bytearray/integ进行来回转换(所有不同类型都是相同的,并进行了几次修改以适合c#类型)

I am creating a socket server to connect and speak with a C# program over TCP. Currently I am trying to create a way to convert the hex sent over the TCP socket to specific variables (the variable type will be in the packet header, and yes I do know tcp is a stream not technically sending packets but I am designing it like this). Currently I have all of the C# integral numeric types converting to and from bytesarray/integers correctly via the code below (All of the different types are the same with a couple edits to fit the c# type)

## SBYTE Type Class definition
## C#/Unity "sbyte" can be from -128 to 127
##
## Usage:
##
## Constructor
## variable = sbyte(integer)
## variable = sbyte(bytearray)
## 
## Variables
## sbyte.integer (Returns integer representation)
## sbyte.bytes (Returns bytearray representation)

class sbyte:

    def __init__(self, input):
        if type(input) == type(int()):
            self.integer = input
            self.bytes = self.__toBytes(input)
        elif type(input) == type(bytearray()):
            self.bytes = input
            self.integer = self.__toInt(input)
        else:
            raise TypeError(f"sbyte constructor can take integer or bytearray type not {type(input)}")
                

    ## Return Integer from Bytes Array
    def __toInt(self, byteArray):
        ## Check that there is only 1 byte
        if len(byteArray) != 1:
            raise OverflowError(f"sbyte.__toInt length can only be 1 byte not {len(byteArray)} bytes")

        ## Return signed integer
        return int.from_bytes(byteArray, byteorder='little', signed=True)


    ## Return Bytes Array from Integer
    def __toBytes(self, integer):

        ## Check that the passed integer is not larger than 128 and is not smaller than -128
        if integer > 127 or integer < -128:
            raise ValueError(f"sbyte.__toBytes can only take an integer less than or equal to 127, and greater than or equal to -128, not \"{integer}\"")

        ## Convert the passed integer to Bytes
        return integer.to_bytes(1, byteorder='little', signed=True)

这适用于我当前实现的所有类型,但是我确实想知道是否有更好的方法来处理此问题?例如使用ctype或其他一些python库.由于这将是一台套接字服务器,因此可能会有尽可能多的连接来尽可能快地处理此问题.或者,如果您发现有什么我可以改善的地方,我很想知道.

This is working for all the types I currently implemented, but I do wonder if there is a better way to handle this? Such as using ctype's or some other python library. Since this will be a socket server with potentially many connections handling this as fast as possible is best. Or if there is anything else you see that I can improve I would love to know.

如果您想要的只是字节数组中的整数值,只需索引该字节数组即可:

If all you want is an integer value from a byte array, simply index the byte array:

>>> b = bytearray.fromhex('1E')
>>> b[0]
30