how to send continuous message from server to client while receiving message from client(using socket.listen and socket.send at the same time

my raspberry pi is the server and Im trying to send continuous message from rpi to android while recieving a command from client (android app),i really dont know if this is possible and how to do it is out of my reach and it is not a feedback message.,, i want to wait for the android client to connect, THEN send messages continuously to the client whilst simultaneously handling the ctrCmd messages from the client.i hope you can help me how it is done thank you..

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();

1 answer

  • answered 2018-01-13 09:49 Ni.

    You should use another socket for that. It's best if you use one socket for each type of communication you need. If the code that receives data from the socket is blocking, you can run it on a separate thread or use a single-threaded async framework like tornado.