Type/to search
Built-in Functions
Global
Version
Sleep
IsVirtual
Mail
Mail_Go
SetErrorFilter
GetPid
GetLastError
GetCommand
GetMeta
Dial
HttpQuery
HttpQuery_Go
Encode
UnixNano
Unix
GetOS
MD5
DBExec
UUID
EventLoop
__Serve
_G
_D
_N
_C
_Cross
JSON.parse
JSON.stringify
SetChannelData
GetChannelData
Log
Market
Trade
Account
Futures
NetSettings
Threads
threading
Thread
getThread
mainThread
currentThread
Lock
Condition
Event
Dict
pending
Thread
ThreadLock
ThreadEvent
ThreadCondition
ThreadDict
Web3
TA
Talib
talib.CDL2CROWS
talib.CDL3BLACKCROWS
talib.CDL3INSIDE
talib.CDL3LINESTRIKE
talib.CDL3OUTSIDE
talib.CDL3STARSINSOUTH
talib.CDL3WHITESOLDIERS
talib.CDLABANDONEDBABY
talib.CDLADVANCEBLOCK
talib.CDLBELTHOLD
talib.CDLBREAKAWAY
talib.CDLCLOSINGMARUBOZU
talib.CDLCONCEALBABYSWALL
talib.CDLCOUNTERATTACK
talib.CDLDARKCLOUDCOVER
talib.CDLDOJI
talib.CDLDOJISTAR
talib.CDLDRAGONFLYDOJI
talib.CDLENGULFING
talib.CDLEVENINGDOJISTAR
talib.CDLEVENINGSTAR
talib.CDLGAPSIDESIDEWHITE
talib.CDLGRAVESTONEDOJI
talib.CDLHAMMER
talib.CDLHANGINGMAN
talib.CDLHARAMI
talib.CDLHARAMICROSS
talib.CDLHIGHWAVE
talib.CDLHIKKAKE
talib.CDLHIKKAKEMOD
talib.CDLHOMINGPIGEON
talib.CDLIDENTICAL3CROWS
talib.CDLINNECK
talib.CDLINVERTEDHAMMER
talib.CDLKICKING
talib.CDLKICKINGBYLENGTH
talib.CDLLADDERBOTTOM
talib.CDLLONGLEGGEDDOJI
talib.CDLLONGLINE
talib.CDLMARUBOZU
talib.CDLMATCHINGLOW
talib.CDLMATHOLD
talib.CDLMORNINGDOJISTAR
talib.CDLMORNINGSTAR
talib.CDLONNECK
talib.CDLPIERCING
talib.CDLRICKSHAWMAN
talib.CDLRISEFALL3METHODS
talib.CDLSEPARATINGLINES
talib.CDLSHOOTINGSTAR
talib.CDLSHORTLINE
talib.CDLSPINNINGTOP
talib.CDLSTALLEDPATTERN
talib.CDLSTICKSANDWICH
talib.CDLTAKURI
talib.CDLTASUKIGAP
talib.CDLTHRUSTING
talib.CDLTRISTAR
talib.CDLUNIQUE3RIVER
talib.CDLUPSIDEGAP2CROWS
talib.CDLXSIDEGAP3METHODS
talib.AD
talib.ADOSC
talib.OBV
talib.ACOS
talib.ASIN
talib.ATAN
talib.CEIL
talib.COS
talib.COSH
talib.EXP
talib.FLOOR
talib.LN
talib.LOG10
talib.SIN
talib.SINH
talib.SQRT
talib.TAN
talib.TANH
talib.MAX
talib.MAXINDEX
talib.MIN
talib.MININDEX
talib.MINMAX
talib.MINMAXINDEX
talib.SUM
talib.HT_DCPERIOD
talib.HT_DCPHASE
talib.HT_PHASOR
talib.HT_SINE
talib.HT_TRENDMODE
talib.ATR
talib.NATR
talib.TRANGE
talib.BBANDS
talib.DEMA
talib.EMA
talib.HT_TRENDLINE
talib.KAMA
talib.MA
talib.MAMA
talib.MIDPOINT
talib.MIDPRICE
talib.SAR
talib.SAREXT
talib.SMA
talib.T3
talib.TEMA
talib.TRIMA
talib.WMA
talib.LINEARREG
talib.LINEARREG_ANGLE
talib.LINEARREG_INTERCEPT
talib.LINEARREG_SLOPE
talib.STDDEV
talib.TSF
talib.VAR
talib.ADX
talib.ADXR
talib.APO
talib.AROON
talib.AROONOSC
talib.BOP
talib.CCI
talib.CMO
talib.DX
talib.MACD
talib.MACDEXT
talib.MACDFIX
talib.MFI
talib.MINUS_DI
talib.MINUS_DM
talib.MOM
talib.PLUS_DI
talib.PLUS_DM
talib.PPO
talib.ROC
talib.ROCP
talib.ROCR
talib.ROCR100
talib.RSI
talib.STOCH
talib.STOCHF
talib.STOCHRSI
talib.TRIX
talib.ULTOSC
talib.WILLR
talib.AVGPRICE
talib.MEDPRICE
talib.TYPPRICE
talib.WCLPRICE
OS
Structures
Built-in Variables

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 supported

Returns

TypeDescription

string

Returns a string recording the IP address and port of the created service. For example: 127.0.0.1:8088, [::]:8089.

Arguments

NameTypeRequiredDescription

serveURI

string

Yes

The serveURI parameter is used to configure the protocol, IP address, port and other settings for service binding, for example: http://0.0.0.0:8088?gzip=true, i.e.: http://:8088?gzip=true.

  • TCP Protocol
    serveURI parameter setting example: tcp://127.0.0.1:6666?tls=true; certificates and private keys can be added, for example: tls=true&cert_pem=xxxx&cert_key_pem=xxxx.
  • HTTP Protocol
    serveURI parameter setting example: http://127.0.0.1:6666?gzip=true; compression settings can be configured: gzip=true.
    serveURI parameter for HTTPS example: https://127.0.0.1:6666?tls=true&gzip=true; cert_pem and cert_key_pem parameters can be added to load certificates.

handler

function

Yes

The handler parameter is used to pass in the route handler function (HTTP protocol), message handler function (TCP protocol), or Stream handler function (WebSocket).

The callback function passed in via the handler parameter can define multiple parameters, with the first parameter being the ctx object (context object).

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 handler parameter, there may be multiple arg parameters, for example:

javascript
__Serve("http://:8088", function(ctx, a, b, c) { Log(`ctx.host():`, ctx.host(), ", a=", a, ", b=", b, ", c=", c) }, 1, 2, 3)

The parameters 1, 2, 3 passed when calling the __Serve() function correspond to the parameters a, b, c of the callback function.

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.

    • WebSocket service is implemented based on HTTP protocol. You can set a routing branch in the path and design the implementation code for WebSocket message 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, calling ctx.query("num") in the callback handler function passed in the handler parameter 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 the User-Agent in the headers of the current request: ctx.header("User-Agent").
  • ctx.method()
    Applies to HTTP protocol, returns the request method when called, such as GET, 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 the ctx context 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. The read method is not supported in regular HTTP protocol; you can specify the timeout parameter timeout_ms in milliseconds.
  • ctx.write(s)
    Applies to HTTP/TCP protocol, used to write string data. You can use JSON.stringify() to encode JSON objects as strings before writing. For WebSocket protocol, this method can be used to pass the encoded string to the client.