组件的Webapi控制器不但可以被Http调用,同时也支持Websocket调用。因此服务启动后相关的Webapi控制器是采用那种方式调用则取决于客户端使用那种方式。
启动服务
首先需要引用BeetleX.FastHttpApi组件,引用后即可定义相关服务.
static void Main(string[] args){ HttpApiServer server = new HttpApiServer(); server.Options.SetDebug(); server.Register(typeof(Program).Assembly); server.Options.Port = 80; server.Options.LogLevel = EventArgs.LogType.Info; server.Options.LogToConsole = true; server.Open(); System.Threading.Thread.Sleep(-1);}
由于控制器是组件内置功能,所以无须再定义WebSocketReceive事件来接管相关处理。
控制器定义
组件定义控制器非常简单,详细可以查看组件的Webapi控制器定义.
[Controller]public class Home{ public string Hello(string name) { return $"Hello {name} {DateTime.Now}"; }}
以上定义一个Hello方法,访问路径/hello.
Web调用
为了方便调需要引用axios.js和beetlex4axios.js两个脚本文件,通过beetlex4axios可以支持http和websocket访问控制器。
<div id="app"> <div> Name: <input type="text" v-model="name" /> <button @click="doSend">发送button> div> <div> <p v-for="item in items">{{item}}p> div> div> <script> var page = new Vue({ el: '#app', data: { hello: new beetlexAction('/hello'), items: [], name: '', }, methods: { doSend() { this.hello.asyncpost({ name: this.name }).then(r => { this.items.push(r); }); }, } });script>
beetlex4axios.js通过beetlexAction对象定义一个控制器访问对象,方法提供asyncpost和asyncget方法,在调用时候依据控制器参数配置即可。针对websocket方法来说asyncpost和asyncget是没有区别的。
由于beetlex4axios.js默认是没有开启websocket的,所以测试请求是http.接下来启用一直websocket.
<div id="app"> <div> Name: <input type="text" v-model="name" /> <button @click="doSend">发送button> div> <div> <p v-for="item in items">{{item}}p> div> div> <script> var page = new Vue({ el: '#app', data: { hello: new beetlexAction('/hello'), items: [], name: '', }, methods: { doSend() { this.hello.asyncpost({ name: this.name }).then(r => { this.items.push(r); }); }, }, mounted() { beetlex.useWebsocket(); } });script>
通过调用beetlex.useWebsocket();方法来开启Websocket,开启后调用就即是Websocket访问。
开启后就可以在浏览器查询对应的Weboskcet message信息,通过这些信息相信能了解到控制调用的数据是怎样打包的,只要通过websocket的基础对象打包对应的请求json数据也可以实现控制器调用。
下载示例
链接:
https://pan.baidu.com/s/1_5qaOq4U3CwLI3wLvDkltQ
提取码:
br20
【BeetleX通讯框架代码详解】
【WebApi示例扩展】
BeetleX
开源跨平台通讯框架(支持TLS)
轻松实现高性能:tcp、http、websocket、redis、rpc和网关等服务应用
https://beetlex.io
如果你想了解某方面的知识或文章可以把想法发送到
henryfan@msn.com|admin@beetlex.io