Nodemcu网络模块学习记录

来源:互联网 发布:os x 10.10优化 编辑:程序博客网 时间:2024/06/06 06:28

1.三种模式

STA:

ESP8266模块通过路由器连接互联网,手机或电脑通过互联网实现对设备的远程控制

AP:

ESP8266模块作为热点,实现手机或电脑直接与模块通信,实现局域网无线控制。

STA+AP:

两种模式的共存模式,即可以通过互联网控制可实现无缝切换,方便操作


2.两个网络模块

wifi模块

net模块


wifi模块下常用API:


wifi.sta.config()

描述

设置station模式下的ssidpassword

语法

wifi.sta.config(ssid, password)

参数

ssid: 字符串,长度小于32字节。

password: 字符串,长度小于64字节。

返回值

nil

示例

    wifi.sta.config("myssid","mypassword")

wifi.sta.connect()

描述

station模式下连接AP

语法

wifi.sta.connect()

参数

nil

返回值

nil

示例

    wifi.sta.connect()


wifi.sta.disconnect()

描述

station模式下与AP断开连接。



wifi.sta.getip()

描述

station模式下获取ip


wifi.ap.config()

描述

设置ap模式下的ssidpassword

语法

wifi.ap.config(cfg)

参数

cfg: 设置APlua table

示例:

     cfg={}

     cfg.ssid="myssid"

     cfg.pwd="mypwd"

     wifi.ap.config(cfg)

返回值

nil

示例

    wifi.ap.config(ssid, 'password')



wifi.ap.getip()

描述

ap模式下获取ip

语法

wifi.ap.getip()

参数

nil

返回值

ip地址字符串,如:"192.168.0.111"

ip地址为0.0.0.0,则返回nil

示例

    wifi.ap.getip()


下面是net模块常用API:


常量

net.TCP, net.UDP

net.createServer()

描述

创建一个server

语法

net.createServer(type, timeout)

参数

type: 取值为:net.TCP或者 net.UDP


net.server子模块:

listen()

描述

侦听指定ip地址的端口。

语法

net.server.listen(port,[ip],function(net.socket))

参数

port: 端口号

ip:ip地址字符串,可以省略

function(net.socket): 连接创建成功的回调函数,可以作为参数传给调用函数。

返回值

nil

示例

    -- 创建一个server

    sv=net.createServer(net.TCP, 30)  -- 30s 超时

    -- server侦听端口80,如果收到数据将数据打印至控制台,并向远端发送‘hello world’

    sv:listen(80,function(c)

      c:on("receive", function(sck, pl) print(pl) end)

      c:send("hello world")

      end)



close()

描述

关闭server

语法

net.server.close()

参数

nil

返回值

nil

示例

    -- 创建server

    sv=net.createServer(net.TCP, 5)

    -- 关闭server

    sv:close()


net.socket模块API:

connect()

描述

连接至远端。

语法

connect(port, ip/domain)

参数

port: 端口号

ip: ip地址或者是域名字符串

返回值

nil



send()

描述

通过连接向远端发送数据。

语法

send(string, function(sent))

参数

string: 待发送的字符串

function(sent): 发送字符串后的回调函数。

返回值

nil



on()

描述

向事件注册回调函数。

语法

on(event, function cb())

参数

event: 字符串,取值为: "connection", "reconnection", "disconnection", "receive", "sent"

function cb(net.socket, [string]): 回调函数。第一个参数是socket.

如果事件是"receive", 第二个参数则为接收到的字符串。

返回值

nil

示例

    sk=net.createConnection(net.TCP, 0)

    sk:on("receive", function(sck, c) print(c) end )

    sk:connect(80,"192.168.0.66")

    sk:send("GET / HTTP/1.1\r\nHost: 192.168.0.66\r\nConnection: keep-alive\r\nAccept: */*\r\n\r\n")



close()

描述

关闭socket

语法

close()

参数

nil

返回值

nil



最后一个:

net.createConnection()

描述

创建一个client

语法

net.createConnection(type, secure)

参数

type: 取值为:net.TCP或者 net.UDP

secure: 设置为1或者0, 1代表安全连接,0代表普通连接。