Python 3 Socket, can't receive data (encode, decode) -


i have game , working networking make multiplayer. created custom module (not best in way), convert 2 values (xy) -1048576 +1048576 , value 0 60 (health), 6 characters. in 6 bytes send information.

but working in python 2, in python 3 discovered couldn't send 'str' characters, used '.encode()' before sending , '.decode()' before using in of functions. doesn't seem work.

i not sure do. help?

module:

#import modules sys import version_info  #------------------------------------------------------------------------------  #funtions #binary string characters def bintomsg(text):     if version_info[0] <= 2: return "".join(chr(int(text[i:i+8], 2)) in range(0, len(text), 8))     else:         data = "".join(chr(int(text[i:i+8], 2)) in range(0, len(text), 8))         return data.encode()  #characters binary string def msgtobin(text):     if version_info[0] <= 2: return "".join('{:08b}'.format(ord(c)) c in text)     else:         text = text.decode()         return "".join('{:08b}'.format(ord(c)) c in text)  #corrects 0's values in binary strings def fixdigit(text, digits):     lenth = digits - len(text)     loop in range(lenth): text = "0" + text     return text  #data characters def datatomsg(x,y,health):      if health >= 2**6 or health < 0: return none     bins = fixdigit(bin(health)[2:],6)     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 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 

this used this...

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} 

when string encoded in utf-8 (default encoding) length increases. if set connection.recv() 6, wouldn't not receive information. chopped pieces. when decode it give error.

to maintain same length found useful encode "cp037".

usage

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

Comments

Popular posts from this blog

android - MPAndroidChart - How to add Annotations or images to the chart -

javascript - Add class to another page attribute using URL id - Jquery -

firefox - Where is 'webgl.osmesalib' parameter? -