【发布时间】:2018-01-13 05:46:28
【问题描述】:
我的树莓派是服务器,我试图从 rpi 向 android 发送连续的消息,同时从客户端(android 应用程序)接收命令,我真的不知道这是否可行,以及如何做到这一点我无法企及这不是反馈消息。,我想等待 android 客户端连接,然后不断地向客户端发送消息,同时处理来自客户端的 ctrCmd 消息。我希望你能帮助我如何完成谢谢。 .
import apptopi
from socket import *
from time import ctime
from nanpy import (ArduinoApi, SerialManager)
apptopi.setup()
connection = SerialManager()
a = ArduinoApi(connection = connection)
ctrCmd = ['Up','Down','Left','Right','Stop','Connect']
add = 0
add += 1
a = str(add) //**this is a sample that i want to send continously
HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)
tcpSerSock = socket(AF_INET, SOCK_STREAM)
tcpSerSock.bind(ADDR)
tcpSerSock.listen(0)
tcpSerSock.send(str.encode(a)) <== i really don't know how to send
continuously
while True:
print 'Waiting for connection'
tcpCliSock,addr = tcpSerSock.accept()
print '...connected from :', addr
try:
while True:
data = ''
data = tcpCliSock.recv(BUFSIZE)
if not data:
break
if data == ctrCmd[0]:
apptopi.forw()
print 'forward'
if data == ctrCmd[1]:
apptopi.back()
print 'backward'
if data == ctrCmd[2]:
apptopi.left()
print 'leftturn'
if data == ctrCmd[3]:
apptopi.right()
print 'rightturn'
if data == ctrCmd[4]:
apptopi.stp()
print 'stop'
except KeyboardInterrupt:
apptopi.close()
GPIO.cleanup()
tcpSerSock.close();
【问题讨论】:
-
当您说“连续发送”时,您的意思是像心跳一样,每隔 x 秒发送一次吗?
-
不是每一秒,这只是我想在收听客户端命令时发送的样本
-
坏主意(状态机不能异步工作)!为此使用两个
socket,但您将花费大量精力来同步。 -
你知道如何在接收的同时发送吗?
标签: python python-2.7 sockets raspberry-pi3 serversocket