通过套接字发送或发送数据的持续时间

时间:2019-07-28 17:08:23

标签: python sockets raspberry-pi

我编写了一些程序,使用套接字通信将数据从树莓派发送到PC。因此,如果我的PC发送命令“ RUN”,我想使树莓保持每秒通过套接字发送数据。如果我的电脑发送命令“ STOP”,则停止。

client.py

.
.
.
def setupSocket():
    try :
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        return s,'CONNECT'
    except socket.error as msg:
        print(msg)


def sendReceive(s, message):
    try:
        s.send(str.encode(message))
        reply = s.recv(1024)
        reply = reply.decode('utf-8')

        print(reply)
        return reply
    except:
        return 'ERR'

if __name__=='__main__':
    s = setupSocket()
    while True:
        data = sendReceive(s,'GET')
        sleep(1)

    s.close()

server.py     进口插座     来自随机进口randint,随机

host = ''
port = 5560


def setupServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created.")
    try:
        s.bind((socket.gethostname(), 5560))
##        s.bind((host, port))
    except socket.error as msg:
        print(msg)
    print("Socket bind comlete.")
    return s

def setupConnection():
    s.listen(1) 
    conn, address = s.accept()
    print("Connected to: " + address[0] + ":" + str(address[1]))
    return conn

def getDustData():
    data = 'some data'
    return str(data)

def GET():
    data = getDustData()
    reply = 'MSG'+' '+data
    return reply

def dataTransfer(conn):
    while True:
        data = conn.recv(1024)
        data = data.decode('utf-8')
        dataMessage = data.split(' ', 1)
        command = dataMessage[0]
        print(command)

        if command == 'GET':
            reply = GET()
        else:
            reply = 'Unknown Command'
        conn.sendall(str.encode(reply))
    conn.close()

if __name__=='__main__':
    s = setupServer()
    while True:
        try:
            conn = setupConnection()
            dataTransfer(conn)
        except:
            pass

所以如果command =='RUN'并且我的客户端继续监听服务器,那么如何使服务器继续发送数据

1 个答案:

答案 0 :(得分:0)

  

如果我的PC发送命令“ RUN”,我想使树莓保持每秒通过套接字发送数据。如果我的电脑发送命令“ STOP”,则停止。

您可以在socket.recv()操作上设置超时,并且在超时时就好像收到了import * as L from 'leaflet'; import 'leaflet-easybutton/src/easy-button'; 命令一样。为此更改

GET

        data = conn.recv(1024)

并添加 try: data = conn.recv(1024) except socket.timeout: data = b'GET' # simulate GET command on timeout RUN命令的处理:

STOP