micropython socket client within _thread issue

65 Views Asked by At

Do you have any idea why a sock server that i run in a thread stops working after handling 1 connection? I'm working on my custom web server and function t_web_server works properly outside the thread, but once i call it via thread it stops working properly. Any no clue why? What do i miss?

import network
import socket
import machine
import json
import _thread

#read configuration for the application
def read_the_config():
    global config
    with open("pogoda.json") as json_data_file:
        config = json.load(json_data_file)

def t_web_server(ip):
    address = (ip, 80)
    connection = socket.socket()
    connection.bind(address)
    connection.listen(1)
    print(connection)
    while True:
        print("Web server is waiting for connection")
        client, client_addr = connection.accept()
        print("Incoming connection from:", str(client_addr))
        try:
            print("handling the client request")
            request = client.recv(2048)
            #request = str(request)
            #new_request(request, client)
            f=open("index.html","r")
            html_main=str(f.read())
            client.send('HTTP/1.0 200 OK\r\nContent-type: text/html\r\n\r\n')
            client.send(html_main)
        except:
            print("ERROR: unable to handle the client")
        print("Closing connection to:", str(client_addr))
        client.close()
    print("exiting")
    return



## read the config variables
read_the_config()
global config


#setting up WiFi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(config['SSID'], config['PASSWORD'])
while wlan.isconnected() == False:
    print('Waiting for WiFi connection...')
    time.sleep(1)
ip = wlan.ifconfig()[0]
print(f'Wifi connected on {ip}')

#initiate web server
_thread.start_new_thread(t_web_server, (ip,) )

while True:
#    t_web_server(ip)
    time.sleep(1)

After making a 1st connection IP address stops responding to ping. There is nothing listening on port 80 anymore and i cannot connect, but while i look on console i see that it waits on connection and there is no error.

0

There are 0 best solutions below