I am new to TCP socket programming. I have a django based server communicating with a microcontroller. Now, I want to implement TCP based socket on the server side in order to communicate with the TCP socket on the microcontroller. Can anyone give me an idea on how to do this ? What libraries should I use on my django server The microprocessor basically opens the socket every 5 seconds and sends a notification to the server. I on the server side should be able to read this and pump data back to the microprocessor using this socket which was opened by the microprocessor.
可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
回答1:
If you are already familiar with django, and your microcontroller supports sending HTTP (REST) requests and can parse Json , you can just add a regular django based view that returns json:
# views.py
from django.http import JsonResponse
def my_view(request):
# handle input here, probably using request.GET / request.POST
return JsonResponse({'status': 'OK'})
However, if your microcontroller is very simple and cannot do HTTP/json, you can use a simple SocketServer from python's standard library instead:
import SocketServer
class MyTCPHandler(SocketServer.BaseRequestHandler):
def handle(self):
self.data = self.request.recv(1024).strip()
print "{} wrote:".format(self.client_address[0])
print self.data
# just send back the same data, but upper-cased
self.request.sendall(self.data.upper())
if __name__ == "__main__":
HOST, PORT = "localhost", 9999
server = SocketServer.TCPServer((HOST, PORT), MyTCPHandler)
server.serve_forever()
Keep in mind you can still import django's libraries and use django's ORM (DB) inside a SocketServer.
Another popular option is to use Tornado's tcpserver:
from tornado.ioloop import IOLoop
from tornado.tcpserver import TCPServer
class MyTCPServer(TCPServer):
def handle_stream(self, stream, address):
def got_data(data):
print "Input: {}".format(repr(data))
stream.write("OK", stream.close)
stream.read_until("\n", got_data)
if __name__ == '__main__':
server = MyTCPServer()
server.listen(9876)
IOLoop.instance().start()