constserver=...// create http server and activate it
server.listen(port,resolve)
constsvr=newWSvr(
server,
[TestController],
asynca=>a
)
create a client project, and try make some messages to the app.
Decorators
Examples
Using WSHandler
You can declare a class method as an event handler, with the @WS and @WSHandler decorator. When decorator @WSParam and @WSCtx are not setted, default args will be data and context.
// ...
@WS()
exportclassTestController{
@WSHandler(MSG_CODE.CS_MSG1)
asyncsample(data:IDataType,ctx:WSContext){
console.log("SC_MSG3 received");
console.log("input is",input);
console.log("context is",ctx);
}
}
Response
If the rsp_code are specified, which are provided as the second param of @WSHandler, the return value will be sent to client as a response.
// ...
@WS()
exportclassTestController{
@WSHandler(MSG_CODE.CS_MSG4,MSG_CODE.SC_MSG4)
asyncsample(data:IDataType,ctx:WSContext){
console.log("SC_MSG3 received");
console.log("input is",input);
console.log("context is",ctx);
returninput;
}
}
Send notice
You can use the method ctx.notice to send a message to any user in connection.
You can use @WSParam decorator to define arguments which are inject by request massage.
In this example, data.arg1 from request message will be insert as the param input.
// ...
@WS()
exportclassTestController{
@WSHandler(MSG_CODE.CS_MSG3)
asyncmethod3(@WSParam("arg1")input:number){
console.log("CS_MSG3 received");
console.log("input is",input);
console.log("context is",ctx);
returninput;
}
}
Using context objects
You can use @WSCtx decorator to define argument which are inject as context.
In this example, ctx will be current WSContext
WSMeta will create a instance of classes who marked by decorator @WS() when necessary, such as when the message arrives.
By default, each class will be instantiated only once, and when instantiated, an empty parameter list will be passed to the constructor.
hard set instance
Sometimes, you may expect to create the service instance by yourself.
In these cases, you can inject the instance into the meta table in the constructor by your self.
@WS()
classNewService{
constructor(
publicreadonlyparamA:any,
publicreadonlyparamB:any
){
WSMeta.inject(this);
}
}
constnewService=newNewService("a","b");
// ...
constsvr=newWSvr(server,[NewService],asynca=>a);
soft set instance
In some another cases, the instantiate method can be a lazy-load implementation.
You can provide getInstance option to inject the instances.