我们怎样才能同时使用tcpSerSock.listen(0)和tcpSerSock.send(str.encode(message))

时间:2018-01-11 10:56:13

标签: python python-2.7 sockets raspberry-pi serversocket

我的覆盆子pi是服务器,我试图从客户端(Android应用程序)接收命令从rpi发送连续消息,我真的不知道这是否可能,如何做到这是我无法达到的这不是反馈信息,我的代码希望你能帮我谢谢。

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 个答案:

答案 0 :(得分:1)

确定一种方法是使用select()函数。 documentation中有关于其操作的信息。

作为一个例子,我已经修改了你的程序版本(见下文)。我没有覆盆子pi,因此部分代码已被注释掉,但您可以根据需要进行替换。

该示例使用select()的超时功能发送&#34;连续&#34;向客户发送消息,同时监控它们的传入消息。您可以调整消息内容和超时,以适合任何适合您的方式。注意,您可能还需要响应客户端消息,因为此代码仅在超时后将数据发送到客户端。做出你需要的任何改变。

import sys
import socket
import select

ctrCmd = ['Up','Down','Left','Right','Stop','Connect']

HOST = ''
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)

tcpSerSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
tcpSerSock.bind(ADDR)

tcpSerSock.listen(1)
print 'Waiting for connection'

sendInterval = 1.0  # interval(sec) for sending messages to connected clients 

rxset = [tcpSerSock]
txset = []
while 1:
    rxfds, txfds, exfds = select.select(rxset, txset, rxset, sendInterval)
    if rxfds:
        for sock in rxfds:
            if sock is tcpSerSock:
                # a client is connecting
                tcpCliSock, addr = tcpSerSock.accept()
                tcpCliSock.setblocking(0)
                rxset.append(tcpCliSock)
                print '...connected from :', addr
            else:
                # a client socket has data or has closed the connection
                try:
                    data = sock.recv(BUFSIZE)
                    if not data:
                        print "...connection closed by remote end"
                        rxset.remove(sock)
                        sock.close()
                    else:
                        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:
                    print "...connection closed by remote end"
                    rxset.remove(sock)
                    sock.close()
    else:
        # timeout - send data to any active client
        for sock in rxset:
            if sock is not tcpSerSock:
                sock.send("Hello!\n") 

我用来测试它的简单客户端程序在这里:

import sys
import socket
import time

ctrCmd = ['Up','Down','Left','Right','Stop','Connect']

HOST = '127.0.0.1'
PORT = 21567
BUFSIZE = 1024
ADDR = (HOST,PORT)

tcpCliSock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

tcpCliSock.connect(ADDR)
time.sleep(1)
for i in range(len(ctrCmd)):
    tcpCliSock.send(ctrCmd[i])
    time.sleep(1)
data = tcpCliSock.recv(BUFSIZE)
print data
tcpCliSock.close()

希望这有帮助,祝你好运。