【问题标题】:Python 3 Socket, can't receive data (encode, decode)Python 3 Socket,无法接收数据(编码,解码)
【发布时间】:2015-07-22 11:26:09
【问题描述】:

我有一个游戏,我正在与一些网络合作以使其成为多人游戏。我创建了一个自定义模块(无论如何都不是最好的),将两个值(XY)从 -1048576 转换为 +1048576 和一个从 0 到 60(健康)的值,转换为 6 个字符。所以我可以用 6 个字节发送所有这些信息。

但这在 Python 2 中有效,在 Python 3 中我发现我无法发送带有字符的“str”,所以我在发送之前使用了“.encode()”和“.decode()”在我的任何功能中使用它之前。但这似乎不起作用。

我不太确定。有什么帮助吗?

模块:

#IMPORT MODULES
from sys import version_info

#------------------------------------------------------------------------------

#FUNTIONS
#Binary String to Characters
def BinToMsg(text):
    if version_info[0] <= 2: return "".join(chr(int(text[i:i+8], 2)) for i in range(0, len(text), 8))
    else:
        data = "".join(chr(int(text[i:i+8], 2)) for i in range(0, len(text), 8))
        return data.encode()

#Characters to Binary String
def MsgToBin(text):
    if version_info[0] <= 2: return "".join('{:08b}'.format(ord(c)) for c in text)
    else:
        text = text.decode()
        return "".join('{:08b}'.format(ord(c)) for c in text)

#Corrects 0's values in Binary Strings
def fixDigit(text, digits):
    lenth = digits - len(text)
    for loop in range(lenth): text = "0" + text
    return text

#Data to Characters
def DataToMsg(x,y,health):

    if health >= 2**6 or health < 0: return None
    bins = fixDigit(bin(health)[2:],6)
    for cord in (x,y):
        if cord >= 2**20: return None
        if cord < 0: bins += "0"
        else: bins += "1"
        bins += fixDigit(bin(int(str(cord).replace("-","")))[2:],20)

    return BinToMsg(bins)

#Characters to Data
def MsgToData(msg):

    bins = MsgToBin(msg)
    data = {"Health":int(bins[:6],2)}
    data["X"] = int(bins[7:27],2)
    data["Y"] = int(bins[28:48],2)
    if bins[6] == "0": data["X"] *= -1
    if bins[27] == "0": data["Y"] *= -1

    return data

这会像这样使用......

Player = {"X":-1234,"Y":5678,"Health":23}
...
connection.send(DataToMsg(Player["X"],Player["Y"],Player["Health"]))
...
print(MsgToData(connection.recv(6))
...
Output: {"X":-1234,"Y":5678,"Health":23}

【问题讨论】:

    标签: python sockets decode encode


    【解决方案1】:

    当字符串以 UTF-8(默认编码)编码时,长度会增加。因此,如果您将 connection.recv() 设置为 6,它将不会接收到所有信息。只是一些切碎的。因此,当您对其进行解码时,它会给您一个错误。

    为了保持相同的长度,我发现将其编码为“cp037”很有用。

    用法

    string.encode("cp037")
    ...
    string.decode("cp037")
    

    【讨论】:

      猜你喜欢
      • 2018-05-05
      • 2016-04-22
      • 1970-01-01
      • 2018-05-06
      • 2018-06-19
      • 1970-01-01
      • 2010-11-18
      • 2017-03-01
      • 2014-06-23
      相关资源
      最近更新 更多