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; }
    }
}
相关推荐
阿里云云原生19 小时前
LoongSuite:解决 WebSocket 全链路可观测性难题,赋能 AI 应用的实时链路追踪
人工智能·websocket·网络协议·阿里云·云原生·可观测
小白勇闯网安圈19 小时前
upload、very_easy_sql、i-got-id-200
python·网络安全·web
0和1的舞者21 小时前
SpringBoot配置文件
java·spring boot·后端·web·配置·spirng
unique_perfect1 天前
vue2与springboot实现deepseek打印机聊天
spring boot·websocket·ai·vue2·deepseek
捧 花2 天前
Go Web 中 WebSocket 原理与实战详解
网络·后端·websocket·网络协议·http·golang·web
想用offer打牌2 天前
一站式了解长轮询,SSE和WebSocket
java·网络·后端·websocket·网络协议·系统架构
代码or搬砖2 天前
flask与vue实现通过websocket通信
vue.js·websocket·flask
曲幽2 天前
Flask路由入门指南:从基础定义到优先级与动态路由转换器
python·flask·web·route·path
2501_921649492 天前
外汇与贵金属行情 API 集成指南:WebSocket 与 REST 调用实践
网络·后端·python·websocket·网络协议·金融
weixin79893765432...2 天前
主流 AI 应用的“流式技术”的探索交流
websocket·sse·ai的流式技术·llm token·http chunked·async generator·message stream