__Serve
The __Serve function is used to create HTTP services, TCP services, and WebSocket services (based on HTTP protocol).
__Serve(serveURI, handler)
__Serve(serveURI, handler, ...args)Examples
javascript
function main() {
let httpServer = __Serve("http://:8088?gzip=true", function (ctx) {
Log("http connect from: ", ctx.remoteAddr(), "->", ctx.localAddr())
let path = ctx.path()
if (path == "/") {
ctx.write(JSON.stringify({
path: ctx.path(),
method: ctx.method(),
headers: ctx.headers(),
cookie: ctx.header("Cookie"),
remote: ctx.remoteAddr(),
query: ctx.rawQuery()
}))
} else if (path == "/tickers") {
let ret = exchange.GetTickers()
if (!ret) {
ctx.setStatus(500)
ctx.write(GetLastError())
} else {
ctx.write(JSON.stringify(ret))
}
} else if (path == "/wss") {
if (ctx.upgrade("websocket")) { // upgrade to websocket
while (true) {
let r = ctx.read(10)
if (r == "") {
break
} else if (r) {
if (r == "ticker") {
ctx.write(JSON.stringify(exchange.GetTicker()))
} else {
ctx.write("not support")
}
}
}
Log("websocket closed", ctx.remoteAddr())
}
} else {
ctx.setStatus(404)
}
})
let echoServer = __Serve("tcp://:8089", function (ctx) {
Log("tcp connect from: ", ctx.remoteAddr(), "->", ctx.localAddr())
while (true) {
let d = ctx.read()
if (!d) {
break
}
ctx.write(d)
}
Log("connect closed")
})
Log("http serve on", httpServer, "tcp serve on", echoServer)
for (var i = 0; i < 5; i++) {
if (i == 2) {
// test Http
var retHttp = HttpQuery("http://127.0.0.1:8088?num=123&limit=100", {"debug": true})
Log("retHttp:", retHttp)
} else if (i == 3) {
// test TCP
var tcpConn = Dial("tcp://127.0.0.1:8089")
tcpConn.write("Hello TCP Server")
var retTCP = tcpConn.read()
Log("retTCP:", retTCP)
} else if (i == 4) {
// test Websocket
var wsConn = Dial("ws://127.0.0.1:8088/wss|compress=gzip")
wsConn.write("ticker")
var retWS = wsConn.read(1000)
Log("retWS:", retWS)
// no depth
wsConn.write("depth")
retWS = wsConn.read(1000)
Log("retWS:", retWS)
}
Sleep(1000)
}
}
python
# Not supported
c++
// Not supportedReturns
| Type | Description |
string | Returns a string recording the IP address and port of the created service. For example: |
Arguments
| Name | Type | Required | Description |
serveURI | string | Yes | The
|
handler | function | Yes | The The callback function passed in via the |
arg | string / number / bool / object / array / function / any (any type supported by the platform) | No | As the actual arguments for the parameters of the callback function passed in via the
The parameters |
See Also
Remarks
-
This function only supports JavaScript language strategies.
-
The service thread is isolated from the global scope, so it does not support closures or references to external variables, custom functions, etc.; however, all platform API functions can be called.
-
WebSocketservice is implemented based on HTTP protocol. You can set a routing branch in the path and design the implementation code forWebSocketmessage subscription/push. Please refer to the example code in this section.
-
The callback handler function passed in the handler parameter receives a ctx parameter. The ctx parameter is a context object used to get data and write data, with the following methods:
- ctx.proto()
Applies to HTTP/TCP protocol, returns the protocol name when called. For example:HTTP/1.1,tcp. - ctx.host()
Applies to HTTP protocol, returns host information when called: IP address, port. - ctx.path()
Applies to HTTP protocol, returns the request path when called. - ctx.query(key)
Applies to HTTP protocol, returns the value corresponding to the key in the query of the request when called. For example, if the request sent is:http://127.0.0.1:8088?num=123, callingctx.query("num")in the callback handler function passed in thehandlerparameter returns"123". - ctx.rawQuery()
Applies to HTTP protocol, returns the raw query in the request (query of the HTTP request) when called. - ctx.headers()
Applies to HTTP protocol, returns the request header information in the request when called. - ctx.header(key)
Applies to HTTP protocol, returns the value corresponding to a specific key in the specified request header when called. For example, to get theUser-Agentin the headers of the current request:ctx.header("User-Agent"). - ctx.method()
Applies to HTTP protocol, returns the request method when called, such asGET,POST, etc. - ctx.body()
Applies to POST requests of HTTP protocol, returns the body of the request when called. - ctx.setHeader(key, value)
Applies to HTTP protocol, sets the request header information of the response message. - ctx.setStatus(code)
Applies to HTTP protocol, sets the HTTP message status code. Usually the HTTP status code is set at the end of the routing branch, default is 200. - ctx.remoteAddr()
Applies to HTTP/TCP protocol, returns the remote client address and port in the request when called. - ctx.localAddr()
Applies to HTTP/TCP protocol, returns the local service address and port when called. - ctx.upgrade("websocket")
Applies to WebSocket protocol implementation based on HTTP protocol, switches thectxcontext object to WebSocket protocol; returns boolean value (true) on successful switch, boolean value (false) on failure. - ctx.read(timeout_ms)
Applies to WebSocket protocol implementation based on HTTP protocol/TCP protocol, reads data from WebSocket connection or TCP connection. Thereadmethod is not supported in regular HTTP protocol; you can specify the timeout parametertimeout_msin milliseconds. - ctx.write(s)
Applies to HTTP/TCP protocol, used to write string data. You can useJSON.stringify()to encode JSON objects as strings before writing. ForWebSocketprotocol, this method can be used to pass the encoded string to the client.