TouchSocket的WebAPI开发服务端

TouchSocket.Net(包括 C# 、VB.Net、F#)的一个整合性的 socket网络通信框架用于TCP通讯,也可以udp、ssl等一系列的通信模块。

大家都使用过其他的Socket产品,那么TouchSocket在设计时也是借鉴了其他产品的优秀设计理念,数据处理适配器就是其中之一,但和其他产品的设计不同的是,TouchSocket的适配器功能更加强大,易用,且灵活。它不仅可以提前解析数据包,还可以解析数据对象,可以随时替换,然后立即生效。例如:可以使用固定包头对数据进行预处理,从而解决数据分包粘包 的问题。也可以直接解析HTTP数据协议、WebSocket数据协议等。

如下示例:

cs 复制代码
using System;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Http;
using TouchSocket.Rpc;
using TouchSocket.Rpc.WebApi;
using TouchSocket.Sockets;

namespace WebApiServerApp
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            WebApiParserPlugin webApiParser = null;
            HttpService service = new HttpService();
            service.Setup(new TouchSocketConfig()
               .UsePlugin()
               .SetListenIPHosts(new IPHost[] { new IPHost(7789) })
               .ConfigureRpcStore(a =>
               {
                   a.RegisterServer<Server>();//注册服务
               })
               .ConfigurePlugins(a =>
               {
                   a.UseCheckClear();
                   webApiParser = a.UseWebApi();
                   a.UseDefaultHttpServicePlugin();//此插件是http的兜底插件,应该最后添加。作用是当所有路由不匹配时返回404.且内部也会处理Option请求。可以更好的处理来自浏览器的跨域探测。
               }))
               .Start();

            Console.WriteLine("以下连接用于测试webApi");
            Console.WriteLine($"使用:http://127.0.0.1:7789/Server/Sum?a=10&b=20");

            //下列代码,会生成客户端的调用代码。
            string codeString = webApiParser.RpcStore.GetProxyCodes("WebApiProxy");
            Console.ReadKey();
        }
    }

    public class Server : RpcServer
    {
        private readonly ILog m_logger;

        public Server(ILog logger)
        {
            this.m_logger = logger;
        }

        [Origin(AllowOrigin = "*")]//跨域设置
        [Router("[api]/[action]ab")]//此路由会以"/Server/Sumab"实现
        [Router("[api]/[action]")]//此路由会以"/Server/Sum"实现
        [WebApi(HttpMethodType.GET)]
        public int Sum(int a, int b)
        {
            return a + b;
        }

        [WebApi(HttpMethodType.POST)]
        public int TestPost(MyClass myClass)
        {
            return myClass.A + myClass.B;
        }

        /// <summary>
        /// 使用调用上下文,响应文件下载。
        /// </summary>
        /// <param name="callContext"></param>
        [WebApi(HttpMethodType.GET, MethodFlags = MethodFlags.IncludeCallContext)]
        public Task<string> DownloadFile(IWebApiCallContext callContext, string id)
        {
            if (id == "rrqm")
            {
                callContext.HttpContext.Response.FromFile(@"D:\System\Windows.iso", callContext.HttpContext.Request);
                return Task.FromResult("ok");
            }
            return Task.FromResult("id不正确。");
        }

        /// <summary>
        /// 使用调用上下文,获取实际请求体。
        /// </summary>
        /// <param name="callContext"></param>
        [WebApi(HttpMethodType.POST, MethodFlags = MethodFlags.IncludeCallContext)]
        [Router("[api]/[action]")]
        public Task<string> PostContent(IWebApiCallContext callContext)
        {
            if (callContext.Caller is ISocketClient socketClient)
            {
                this.m_logger.Info($"IP:{socketClient.IP},Port:{socketClient.Port}");//获取Ip和端口
            }
            if (callContext.HttpContext.Request.TryGetContent(out byte[] content))
            {
                this.m_logger.Info($"共计:{content.Length}");
            }

            return Task.FromResult("ok");
        }
    }

    public class MyClass
    {
        public int A { get; set; }
        public int B { get; set; }
    }
}
相关推荐
2501_915918416 小时前
接口漏洞怎么抓?Fiddler 中文版 + Postman + Wireshark 实战指南
websocket·网络协议·tcp/ip·http·网络安全·https·udp
OEC小胖胖7 小时前
深入理解 Vue.js 响应式原理及其在 Web 前端开发中的应用
开发语言·前端·javascript·vue.js·web
游戏开发爱好者82 天前
iOS重构期调试实战:架构升级中的性能与数据保障策略
websocket·网络协议·tcp/ip·http·网络安全·https·udp
却道天凉_好个秋2 天前
音视频学习(三十六):websocket协议总结
websocket·音视频
OEC小胖胖2 天前
告别 undefined is not a function:TypeScript 前端开发优势与实践指南
前端·javascript·typescript·web
2501_916013742 天前
iOS 多线程导致接口乱序?抓包还原 + 请求调度优化实战
websocket·网络协议·tcp/ip·http·网络安全·https·udp
夏天想2 天前
优化 WebSocket 实现单例连接用于打印【待测试 】
网络·websocket·网络协议
aiprtem2 天前
基于Flutter的智能设备web前端设计
物联网·flutter·web
skywalk81632 天前
2025年的前后端一体化CMS框架优选方案
cms·web
2501_915921433 天前
Fiddler 中文版怎么配合 Postman 与 Wireshark 做多环境接口调试?
websocket·网络协议·tcp/ip·http·网络安全·https·udp