简体   繁体   中英

How to send unsigned characters over TCP in this communication protocol format in Python?

So, I'm working on a project with a proprietary communication protocol. I need to send data in given format and Up, Down, Left & Right co-ordinates to particular IP address. Communication happens over TCP and I need to program TCP client in python to send data in following format:

IP address/Handshake address: 192.166.166.166

This is the Data format .

Data type is unsigned char 0-255 (8-bit binary) and data length is 6-64 bit.

Data length of each frame is 10-64 bit.

So, If I want to move object at 1.0.0.1 to (23, 45, 67, 89), this is the given instruction:

Send 255 255 10 3 1 0 0 1 23 45 67 89 to specified IP address. I imagine specified IP address is 192.166.166.166. You can refer to data format to understand this data that I'm supposed to send. It's quite simple.

The question is, how am I supposed to send this series of unsigned chars over TCP in python?

I've tried following:

import socket
host = '192.166.166.166'
port = 80                   # 80 Because TCP

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

data = '255 255 10 3 1 0 0 1 23 45 67 89'
s.sendall(data)
result = s.recv(1024)
s.close()
print('Received', repr(result))

Obviously this is not working. I've not specified unsigned char and I'm just sending raw data and spaces.

This is what I get in return from server:

('Received', '\'HTTP/1.0 400 Bad Request\\r\\nServer: Mini-IoT-314\\r\\nDate: , 31  1969 23:59:59 GMT\\r\\nPragma: no-
cache\\r\\nCache-Control: no-cache\\r\\nContent-Type: 
text/html\\r\\nConnection: close\\r\\n\\r\\n<HTML><HEAD><TITLE>400 Bad 
Request</TITLE></HEAD>\\n<BODY BGCOLOR="#cc9999"><H4>400 Bad 
Request</H4>\\nCan\\\'t parse request.\\n</BODY></HTML>\\n\'')

Now, I'm not sure what to do and how to send this data so server can process this data appropriately. I would really appreciate a help here.

Not really my area of expertise, just an idea: You might need to send the data as a Structure.

Have a look at python's ctypes: https://docs.python.org/3/library/ctypes.html#structured-data-types

from ctypes import *

class payload(Structure):
    _fields_ = [("data_sign1", c_ubyte),
                  ...]

1) I tested your code in python 3.5 with slight modifications rather than sending string,i sent bytes by converting string into bytes

bytes(data,'utf-8')

2) Do not use Port 80,might be your http server is running on that port, Try to use some other port. it will work

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM