Skip to content

Lua API reference manual

zhaojh329 edited this page Jun 5, 2017 · 11 revisions

API for evmongoose

init

Init mgr context, return a handle

local ev = require("ev")
local evmongoose = require("evmongoose")

--use default loop
local loop = ev.Loop.default
local mgr = evmongoose.init()

--use alloced loop
local loop = ev.Loop.new()
local mgr = evmongoose.init(loop)

bind

Listens for the specified address, can plain udp, plain tcp, or http or https.

--an tcp server
mgr:bind("8000", ev_handle)

--an http server
mgr:bind("8000", ev_handle, {proto = "http", document_root = "/www"})

--an https server
mgr:bind("8000", ev_handle, {proto = "http", ssl_cert = "server.pem", ssl_key = "server.key", document_root = "."})

connect_http

connect to http or https server

mgr:connect_http("http://www.baidu.com", ev_handle)
mgr:connect_http("https://www.baidu.com", ev_handle, {ssl_cert = "server.pem", ssl_key = "server.key"})

connect

connect to tcp server or mqtt server

mgr:connect("localhost:1883", ev_handle)

ev_handle

an event callback function, when the function is called, the bottom layer will passes in 3 parameters. They are "nc", "event", "msg". "nc" is used to identify each connection, "event" represents the current event type, "msg" saves the relevant data of the current particular event.

local function ev_handle(nc, event, msg)
	if evmongoose.MG_EV_HTTP_REQUEST then
		...
	end
end

event type

  • MG_EV_CONNECT
  • MG_EV_CLOSE
  • MG_EV_HTTP_REQUEST
  • MG_EV_HTTP_REPLY
  • MG_EV_MQTT_CONNACK
  • MG_EV_MQTT_SUBACK
  • MG_EV_MQTT_PUBACK
  • MG_EV_MQTT_PUBLISH
  • MG_EV_MQTT_CONNACK_ACCEPTED
  • MG_EV_MQTT_CONNACK_UNACCEPTABLE_VERSION
  • MG_EV_MQTT_CONNACK_IDENTIFIER_REJECTED
  • MG_EV_MQTT_CONNACK_SERVER_UNAVAILABLE
  • MG_EV_MQTT_CONNACK_BAD_AUTH
  • MG_EV_MQTT_CONNACK_NOT_AUTHORIZED

print

send data to http client

mgr:print(nc, "test")

print_http_chunk

Sends a HTTP chunk http client.

mgr:print_http_chunk(nc, "test")
mgr:print_http_chunk(nc, "")

http_send_redirect

Sends a redirect response.

mgr:http_send_redirect(nc, 301, "http://www.baidu.com")

send_websocket_frame

Send WebSocket frame to the remote end

mgr:send_websocket_frame(nc, "I is evmg")

send

Sends data to the connection.

mgr:send(nc, data)

set_protocol_mqtt

mqtt_subscribe

Subscribes to a bunch of topics.

local topic = "evmongoose"
local msg_id = 12
mgr:mqtt_subscribe(nc, topic, msg_id);

mqtt_publish

Publishes a message to a given topic.

mgr:mqtt_publish(nc, "test", "12345678")