Search code examples
pythonsocketsesp8266

How to break while loop when a new message arrives?


I have used Python socket in ESP as a server and Laptop as a client. I customized the socket codes from this site. When I send the loop as the client input, I enter a loop on the server. I don't know how the while loop is broken when I send a word other than loop, For example "Hello".

server.py:

import socket

host = ''
port = 5560

def setupServer():
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    print("Socket created.")
    try:
        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 Hello_():
    print('Hello')

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

        if command == 'loop':
            Loop_()
        if command == 'Hello':
            Hello_()         
        else:
            print("X")

    conn.close()

s = setupServer()

while True:
    try:
        conn = setupConnection()
        dataTransfer(conn)
    except:
        break

client.py

import socket

host = '192.168.56.1'
port = 5560

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, port))

while True:
    command = input("Enter your command: ")
    s.send(str.encode(command))
    
s.close()

I know your time is valuable and I appreciate your attention for spending time for help me.


Solution

  • If you want the Loop_() method to return when more data is received on the socket, you can modify the method so that it calls select() to poll the socket to see if more data has arrived, as shown below. (Note that I've added a conn argument to the Loop_() method so I can pass in the socket to check it)

    import select
    
    [...]
    
    def Loop_(conn):
        while True:
            print('yes')
            inReady, outReady, exReady = select.select([conn], [], [], 0.0)
            if (conn in inReady):
               print('more data has arrived at the TCP socket, returning from Loop_()')
               break
    
    def dataTransfer(conn):
        while True:
            data = conn.recv(1024)
            data = data.decode('utf-8')
            dataMessage = data.split(' ', 1)
            command = dataMessage[0]
    
            if command == 'loop':
                Loop_(conn)
            if command == 'Hello':
                Hello_()
            else:
                print("X")
    
        conn.close()