Problem with simple socket loop

All ESP8266 boards running MicroPython.
Official boards are the Adafruit Huzzah and Feather boards.
Target audience: MicroPython users with an ESP8266 board.
Post Reply
upymar
Posts: 18
Joined: Sat Feb 04, 2017 7:47 am

Problem with simple socket loop

Post by upymar » Tue Jun 23, 2020 9:11 am

Hi community,

I have configured my esp8266 as access point and want it to react on certain data send from a smartphone over a socket it listens on.
This is my code:

Code: Select all

import usocket as socket
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]

while True:
    s = socket.socket()
    s.bind(addr)
    s.listen(1)
    cl, addr = s.accept()
    data=str(cl.recv(1024))
    if data[-2] == "0":
        print(data[-2])
    elif data[-2] == "1":
        print(data[-2])
    s.close()
The loop runs once and gives the right output and then nothing happens. I can only break it with Ctrl+C.
I read that I have to put the s=socket.socket() line into the loop. Is that right?

Can you please help me?

User avatar
jimmo
Posts: 2754
Joined: Tue Aug 08, 2017 1:57 am
Location: Sydney, Australia
Contact:

Re: Problem with simple socket loop

Post by jimmo » Mon Jun 29, 2020 6:46 am

upymar wrote:
Tue Jun 23, 2020 9:11 am
I read that I have to put the s=socket.socket() line into the loop. Is that right?
You need to create the listening socket once, then accept each incoming connection in a loop.

Code: Select all

s = socket.socket()
s.bind(addr)
s.listen(1)

while True:
    cl, addr = s.accept()
    data=str(cl.recv(1024))
    if data[-2] == "0":
        print(data[-2])
    elif data[-2] == "1":
        print(data[-2])
    s.close()

Post Reply