开发者

Two-way Socket I/O with asyncore or alternative in Python

开发者 https://www.devze.com 2023-03-14 14:00 出处:网络
Am working on the back-end of Django web app that also has to do socket I/O with sensor devices in the field via GPRS using TCP communication.

Am working on the back-end of Django web app that also has to do socket I/O with sensor devices in the field via GPRS using TCP communication.

I'd managed to succeed in obtaining data from the devices using the python module asyncore. What I've been doing was configuring the devices to send data via TCP to the server, and then I would pick up this incoming data using asyncore (which I chose because of it's asynchronous approach to socket i/o).

The docs talk of overloading the asyncore.dispatcher or asyncore.dispatcher_with_send in order to be able to implement custom actions in the callbacks like handle_write, handle_read, etc.

Currently, am able to obtaining incoming data by picking it up in the handle_read method, but a new requirement came up recently:

It is required to be able to hold onto the connection when a device connects to the server, so that we can send to it some commands (say like requiring it to identify itself), and thereafter continue to use it's sent data 开发者_运维技巧once found genuine.

So, I'd added code in the handle_write method in my implementation, code to send the "identify yourself" commands to the device that has connected to us. But my problem is that this code never executes even when devices continue to connect and the handle_read shows I can obtain the incoming data!

I tried putting the "identify yourself" code (that sends some hex commands like below)

print 'Attempting to Identify Remote Party...'
self.send('\x40\x40\x00\x11\x12\x34\x56\xFF\xFF\xFF\xFF\x90\x01\x41\xCF\x0D\x0A')

hoping that a response would then come in via handle_read while I hold onto the data that was sent previously, but this fails! What can I do?

What is the better /best way to pull this off?


If you are implementing a protocol which has some commands and some data exchange, then it is better to use the asynchat library along with asyncore.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号