Micropython学习交流群 学习QQ群:786510434 提供多种固件下载和学习交流。

Micropython-扇贝物联 QQ群:31324057 扇贝物联是一个让你与智能设备沟通更方便的物联网云平台

Micropython学习交流群 学习QQ群:468985481 学习交流ESP8266、ESP32、ESP8285、wifi模块开发交流、物联网。

Micropython老哥俩的IT农场分享QQ群:929132891 为喜欢科创制作的小白们分享一些自制的计算机软硬件免费公益课程,由两位多年从事IT研发的中年大叔发起。

Micropython ESP频道

micropython esp32 sockets 创建服务端


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)



推荐分享
图文皆来源于网络,内容仅做公益性分享,版权归原作者所有,如有侵权请告知删除!
 

Copyright © 2014 ESP56.com All Rights Reserved

执行时间: 0.010096073150635 seconds