【问题标题】:how to send continuous message from server to client while receiving message from client(using socket.listen and socket.send at the same time如何在从客户端接收消息的同时从服务器向客户端发送连续消息(同时使用socket.listen和socket.send
【发布时间】: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


【解决方案1】:

您应该为此使用另一个套接字。最好为所需的每种通信类型使用一个套接字。如果从套接字接收数据的代码是阻塞的,您可以在单独的线程上运行它或使用单线程异步框架,如 tornado。

【讨论】:

  • 好吧,你需要一个例子做什么?有很多使用套接字、线程和龙卷风的例子......
猜你喜欢
  • 2017-01-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多