socket problem
Posted: Thu Nov 09, 2017 5:29 pm
I'm trying to make a very basic server based on the example here: https://docs.micropython.org/en/latest/ ... k_tcp.html
The code below works as expected the first time I run it. But if I run the same program again I get "OSError: 112" on the line with "s.bind(addr)". Changing the port or doing a hard reset solves this.
I think the problem is that I'm trying to bind a port that is already in use. (?)
Any suggestions for how to solve this? Is there a way to unbind all ports?
import socket
import network
#Code for connecting to wifi left out.
html = "<!DOCTYPE html><html><head><title>Test</title></head><body><h1>Hello World!</h1></body></html>"
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
cl, addr = s.accept()
print('client connected from', addr)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
response = html
cl.send(response)
cl.close()
The code below works as expected the first time I run it. But if I run the same program again I get "OSError: 112" on the line with "s.bind(addr)". Changing the port or doing a hard reset solves this.
I think the problem is that I'm trying to bind a port that is already in use. (?)
Any suggestions for how to solve this? Is there a way to unbind all ports?
import socket
import network
#Code for connecting to wifi left out.
html = "<!DOCTYPE html><html><head><title>Test</title></head><body><h1>Hello World!</h1></body></html>"
addr = socket.getaddrinfo('0.0.0.0', 80)[0][-1]
s = socket.socket()
s.bind(addr)
s.listen(1)
print('listening on', addr)
while True:
cl, addr = s.accept()
print('client connected from', addr)
cl_file = cl.makefile('rwb', 0)
while True:
line = cl_file.readline()
if not line or line == b'\r\n':
break
response = html
cl.send(response)
cl.close()