from uhttp import requests
import socket
import threading
import network
import time
from machine import Pin
serverip = '0.0.0.0'
port = 8080
buffsize = 4096
def do_connect():
wlan = network.WLAN(network.STA_IF) # 以工作站 (wlan) 模式运行,需要创建一个工作站Wi-Fi接口的实例
wlan.active(True) # 在工作站对象上调用激活方法并以True作为输入值传递来激活网络接口
start_time=time.time() # 记录开始时间
if not wlan.isconnected(): # 如果尚未联网成功
print("当前无线未联网,正在连接中....")
wlan.connect("NBWIFI", "xxxxx") # 无线网SSID、密码,开始联网
while not wlan.isconnected(): # 如果还未连接成功,则LED灯闪烁提示
time.sleep_ms(1000)
print("正在尝试连接到wifi....")
print(time.time())
if time.time()-start_time>15: # 如果超过15秒还不行,就退出
print("连接失败!!!无线网连接超过15秒,请检查无线网名称和密码是否正确..")
break
if wlan.isconnected(): # 如果联接成功
IP_info=wlan.ifconfig()
print("无线网已经连接,信息如下:")
print("IP地址:"+IP_info[0])
global serverip
serverip=IP_info[0]
print("子网掩码:"+IP_info[1])
print("网关:"+IP_info[2])
print("DNS:"+IP_info[3])
ip_address = wlan.ifconfig()[0]
print("ip_address "+ip_address)
do_connect()
listenSocket=None
#####################
print("serverip:"+serverip)
#####################
try:
listenSocket = socket.socket() #create socket
listenSocket.bind((serverip,port)) #bind ip and port
listenSocket.listen(1) #listen message
listenSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) #Set the value of the given socket option
print ('tcp waiting...')
while True:
print("accepting.....")
conn,addr = listenSocket.accept() #Accept a connection,conn is a new socket object
print(addr,"connected")
while True:
data = conn.recv(1024) #Receive 1024 byte of data from the socket
if(len(data) == 0):
print("close socket")
conn.close() #if there is no data,close
break
print(data)
ret = conn.send("123456") #send data
except:
if(listenSocket):
listenSocket.close()
wlan.disconnect()
wlan.active(False)