iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > 其他教程 >C#中C/S端实现WebService服务
  • 291
分享到

C#中C/S端实现WebService服务

2024-04-02 19:04:59 291人浏览 安东尼
摘要

目录前言一、实现思路二、步骤1.使用HttpListener构建服务2.处理请求的数据总结前言 使用 C#以B/S方式构建WEBService服务十分简便,即是使用asp.net在网

前言

使用 C#以B/S方式构建WEBService服务十分简便,即是使用asp.net在网站中添加WebService服务并使用IIS发布。但如需要在C/S程序中发布WebService服务则没有直接可用的类库。因此需要使用另外的方式实现WebService服务。

一、实现思路

WebService实际是使用Http并遵循SOAP协议格式进行交互。能够进行Http通讯即可实现WebService服务,只是没了现成的类库就需要自己编写解析SOAP格式数据包和组织应答包。

二、步骤

1.使用HttpListener构建服务

代码如下(示例):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
using System.net;
using System.Web;

namespace LadarManufacturabilityTooling
{
    public class httpservic
    {
        public delegate byte[] OnGetResponseDataHandle(HttpListenerPostValue Sender);
        public event OnGetResponseDataHandle OnGetResponse;

        private static HttpListener httpPostRequest = new HttpListener();
        private static bool IsRun = true;
        public HttpServic(IPAddress HttpServerIP, int HttpServerPort)
        {
            httpPostRequest.Prefixes.Add("http://" + HttpServerIP.ToString() + ":" + HttpServerPort.ToString() + "/");

            try
            { 
                httpPostRequest.Start();
            }
            catch(Exception ex)
            {
                string Mes = ex.Message;
            }

            Thread ThrednHttpPostRequest = new Thread(new ThreadStart(httpPostRequestHandle));
            ThrednHttpPostRequest.Start();
        }

        private void httpPostRequestHandle()
        {
            while (IsRun)
            {
                try
                { 
                    HttpListenerContext requestContext = httpPostRequest.GetContext();
                    Thread threadsub = new Thread(new ParameterizedThreadStart((requestcontext) =>
                    {
                        HttpListenerContext request = (HttpListenerContext)requestcontext;
                        //获取Post请求中的参数和值帮助类  
                        HttpListenerPostParaHelper httppost = new HttpListenerPostParaHelper(request);
                        //获取Post过来的参数和数据  
                        HttpListenerPostValue lst = httppost.GetHttpListenerPostValue();

                        byte[] buffer = null;
                        if (lst != null)
                        {
                            if(OnGetResponse != null)
                                buffer = OnGetResponse(lst);
                        }

                        if(buffer != null)
                        {//Response  
                            try
                            { 
                                request.Response.StatusCode = 200;
                                request.Response.Headers.Add("SOAPAction", "");
                                request.Response.Headers.Add("User-Agent", "gSOAP/2.8");
                                request.Response.ContentType = "text/xml; charset=utf-8";
                                request.Response.ContentEncoding = Encoding.UTF8;
                                request.Response.ContentLength64 = buffer.Length;
                                var output = request.Response.OutputStream;
                                output.Write(buffer, 0, buffer.Length);
                                output.Close();
                            }
                            catch(Exception ex2)
                            {
                            }
                        }
                        else
                        {
                            try
                            { 
                                request.Response.Close();
                            }
                            catch
                            { }
                        }
                    }));
                    threadsub.Start(requestContext);
                }
                catch (Exception ex)
                {
                    string Mes = ex.Message;
                }
            }
        }
        
        public void StopHttpThread()
        {
            IsRun = false;
            httpPostRequest.Abort();
        }
    }
}

启动服务后在httpPostRequestHandle()函数中编写对监听到的服务请求的处理。

//获取Post过来的参数和数据  
HttpListenerPostValue lst = httppost.GetHttpListenerPostValue();

GetHttpListenerPostValue();函数作用为取出请求中的数据部分和请求的名称。涉及到的类定义和代码如下:

/// <summary>  
    /// HttpListenner监听Post请求参数值实体  
    /// </summary>  
    public class HttpListenerPostValue
    {
        /// <summary>  
        /// 0=> 参数  
        /// 1=> 文件  
        /// </summary>  
        public int type = 0;
        /// <summary>
        /// 请求的类型名称
        /// </summary>
        public string name;
        /// <summary>
        /// 数据字符串
        /// </summary>
        public string datas;
    }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.IO;

namespace LadarManufacturabilityTooling
{
    /// <summary>  
    /// 获取Post请求中的参数和值帮助类  
    /// </summary>  
    public class HttpListenerPostParaHelper
    {
        private HttpListenerContext request;

        public HttpListenerPostParaHelper(HttpListenerContext request)
        {
            this.request = request;
        }

        /// <summary>  
        /// 获取Post过来的参数和数据  
        /// </summary>  
        /// <returns></returns>  
        public HttpListenerPostValue GetHttpListenerPostValue()
        {
            try
            {
                HttpListenerPostValue HttpListenerPostValueList = new HttpListenerPostValue();
                if (true)
                {
                    Stream body = request.Request.InputStream;
                    Encoding encoding = Encoding.UTF8;
                    StreamReader reader = new System.IO.StreamReader(body, encoding);
                    if (request.Request.ContentType != null)
                    {
                        Console.WriteLine("Client data content type {0}", request.Request.ContentType);
                    }
                    string datas = reader.ReadToEnd();
                    string Requestname = request.Request.RawUrl.Replace("/","");
                    HttpListenerPostValueList.datas = datas;
                    HttpListenerPostValueList.name = Requestname;
                    Console.WriteLine(datas);
                }
                return HttpListenerPostValueList;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
    }
}

以上部分和构建普通的http监听服务并无区别。

2.处理请求的数据

OnGetResponse事件用于处理请求的数据并组织回包

代码如下(示例):

private byte[] ThisHttpServic_OnGetResponse(HttpListenerPostValue Sender)
        {
            byte[] buffer = null;
            string restr = "";
            //处理收到的请求
            switch (Sender.name)
            {
                case "MyServiceName":
                {
                    string xmlOrgstr = "";
                    int iStartPos = Sender.datas.IndexOf("<xmlData>", 1);
                    int iStopPos = Sender.datas.IndexOf("</xmlData>", 1);
                    if (iStartPos > 0)
                    {
                        xmlOrgstr = Sender.datas.Substring(iStartPos + 9, iStopPos - iStartPos - 9);
                    }
                    string xmlstr = HttpUtility.htmlDecode(xmlOrgstr);
                    string LOGIN_ACK = GetPack(xmlstr);
                    restr = GetCompleteSoapString(System.Security.SecurityElement.Escape(LOGIN_ACK));
                    break;
                }
                default:
                    restr = "";
                    break;
            }

            buffer = System.Text.Encoding.UTF8.GetBytes(restr);
            return buffer;
        }

需要从收到的http请求的数据部分提取出WebService服务的参数。

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:client1="http://LSCService.chinamobile.com" xmlns:service1="http://FSUService.chinamobile.com">

<SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">

<client1:invoke>

<xmlData>&lt;?xml version="1.0" encoding="UTF-8" ?&gt;&lt;Request&gt;&lt;PK_Type&gt;&lt;Name&gt;LOGIN&lt;/Name&gt;&lt;/PK_Type&gt;&lt;Info&gt;&lt;UserName&gt;cmcc&lt;/UserName&gt;&lt;PassWord&gt;B101341CC2E4D6F5B395C7544B96A826&lt;/PassWord&gt;&lt;FSUID&gt;21202110060001&lt;/FSUID&gt;&lt;FSUIP&gt;192.168.1.253&lt;/FSUIP&gt;&lt;FSUMac&gt;00:21:92:01:b5:9f&lt;/FSUMAC&gt;&lt;FSUVER&gt;2.0.0.15 for CMCC&lt;/FSUVER&gt;&lt;/Info&gt;&lt;/Request&gt;&#xD;&#xA;

</xmlData>

</client1:invoke><

/SOAP-ENV:Body>

</SOAP-ENV:Envelope>

收到的数据包原文(Sender.datas)为:

作为示例的服务的参数名为xmlData从SOAP中截取出参数的字符串进行处理。

由于xmlData中的内容是一串xml字符,SOAP传输时经过了转义,因此还需要转义回来。

string xmlstr = HttpUtility.HtmlDecode(xmlOrgstr);

处理完相应的业务,将需要回复的数据加上SOAP协议的头尾组好回复包返回。需要转义的部分记得进行符号转义。

System.Security.SecurityElement.Escape(LOGIN_ACK)

SOAP协议的头尾根据WebService服务函数的定义有所不同,需要自行组织。示例如下:

        /// <summary>
        /// 返回完整的SOAP包
        /// </summary>
        /// <param name="XmlData">应答部分</param>
        /// <returns></returns>
        public static string GetCompleteSoapString(string XmlData)
        {
            string restr = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
            + "<SOAP-ENV:Envelope xmlns:SOAP-ENV=\"http://schemas.xmlsoap.org/soap/envelope/\""
            + " xmlns:SOAP-ENC=\"http://schemas.xmlsoap.org/soap/encoding/\""
            + " xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\""
            + " xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\""
            + " xmlns:client1=\"http://LService.mobile.com\""
            + " xmlns:service1=\"http://FService.mobile.com\">"
            + "<SOAP-ENV:Body>"
            + "<client1:invokeResponse><invokeReturn>";
            string restrEnd = "</invokeReturn></client1:invokeResponse></SOAP-ENV:Body></SOAP-ENV:Envelope>";
            restr = restr + XmlData + restrEnd;
            return restr;
        }

总结

既然C# 并未提供在C/S程序使用的WebService服务的.Net库,那么就使用HttpListener监听http请求自行解出其中的输入数据,再根据SOAP协议进行处理。以此方式实现WebService服务。

到此这篇关于C#中C/S端实现WebService服务的文章就介绍到这了,更多相关C# C/S端 WebService 内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: C#中C/S端实现WebService服务

本文链接: https://www.lsjlt.com/news/165006.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • C#中C/S端实现WebService服务
    目录前言一、实现思路二、步骤1.使用HttpListener构建服务2.处理请求的数据总结前言 使用 C#以B/S方式构建WebService服务十分简便,即是使用Asp.net在网...
    99+
    2024-04-02
  • python用c/s实现服务器简单管理
    由于有大量的windows虚拟机用来做一些任务。这些windows上的机器程序要经常更新。每次部署升级,需要一台台的远程桌面上去操作,进行简单升级操作。这样讲花费大量时间。并且伴随windows机器的增加,将更加难管理。 无需远程桌面,...
    99+
    2023-01-31
    简单 服务器 python
  • java如何实现post请求webservice服务端
    目录post请求webservice服务端1.例如我此时有一个wsdl文件2.点击row查看具体的发送参数3.代码实现3.1参数说明用post请求调用webservicepost请求...
    99+
    2024-04-02
  • C#中怎么实现服务端与客户端通信
    C#中怎么实现服务端与客户端通信,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。C#服务端与客户端通信实现实例:TcpClient client;&nb...
    99+
    2023-06-17
  • C#中如何实现服务端与客户端通信
    这篇文章将为大家详细讲解有关C#中如何实现服务端与客户端通信,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。C#服务端与客户端通信实现实例:class Server {&n...
    99+
    2023-06-17
  • C#中怎么实现服务端与客户端连接
    这篇文章将为大家详细讲解有关C#中怎么实现服务端与客户端连接,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。C#服务端与客户端连接实现实例:class Client {&n...
    99+
    2023-06-17
  • golang实现webservice服务
    随着微服务架构的普及和Web服务的需求增加,越来越多的开发者开始使用Golang来实现Web服务。Golang是一种轻量级的语言,拥有快速的编译速度和卓越的性能,使其成为实现Web服务的理想选择。在本文中,我们将讨论如何使用Golang实现...
    99+
    2023-05-14
  • Spring Boot 实现Restful webservice服务端示例代码
    1.Spring Boot configurationsapplication.ymlspring: profiles: active: dev mvc: favicon: enabled: false datasource: drive...
    99+
    2023-05-30
    spring boot webservice
  • 如何实现C#服务端与客户端连接
    今天就跟大家聊聊有关如何实现C#服务端与客户端连接,可能很多人都不太了解,为了让大家更加了解,小编给大家总结了以下内容,希望大家根据这篇文章可以有所收获。C#服务端与客户端连接实现的时间性:当服务器开始对端口侦听之后,便可以创建客户端与它建...
    99+
    2023-06-17
  • C/S架构学习之多线程实现TCP并发服务器
    并发概念:并发是指两个或多个事件在同一时间间隔发生;多线程实现TCP并发服务器的实现流程:一、创建套接字(socket函数):通信域选择IPV4网络协议、套接字类型选择流式; int sockfd =...
    99+
    2023-10-24
    c语言 架构 学习 linux tcp/ip 多线程 并发服务器
  • C语言中怎么实现一个socket.io服务器端
    C语言中怎么实现一个socket.io服务器端,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。在运行socket.io_server之前,需要安装以下依赖:sud...
    99+
    2023-06-17
  • C#实现MQTT服务端与客户端通讯功能
    关于MQTT MQTT(消息队列遥测传输)是ISO 标准(ISO/IEC PRF 20922)下基于发布/订阅范式的消息协议。它工作在 TCP/IP协议族上,是为硬件性能低下的远程设...
    99+
    2024-04-02
  • C#中怎么侦听服务端端口
    这篇文章给大家介绍C#中怎么侦听服务端端口,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。C#服务端端口侦听实例演示:using System.Net;   // 引入这...
    99+
    2023-06-17
  • C#用websocket实现简易聊天功能(服务端)
    C# 利用websocket实现简易聊天功能——服务端,供大家参考,具体内容如下 前言 使用C#语言进行开发,基于.NET FrameWork4功能包含群聊,...
    99+
    2024-04-02
  • C++编写的WebSocket服务端客户端实现示例代码
    目录使用过标准的libwebsockets服务端库测试过,主要是短小精悍,相对于libwebsockets不需要依赖zlib和openssl 以及其他库,直接make就可以使用了,l...
    99+
    2024-04-02
  • C#如何实现MQTT服务端与客户端通讯功能
    这期内容当中小编将会给大家带来有关C#如何实现MQTT服务端与客户端通讯功能,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。关于MQTTMQTT(消息队列遥测传输)是ISO 标准(ISO/IEC PRF 2...
    99+
    2023-06-29
  • TCP服务器的C#实现
    TCP实现类 internal class TcpServer { public Socket ServerSocket { get; set; } public D...
    99+
    2023-09-04
    tcp/ip 服务器 c#
  • SpringBoot整合WebService服务的实现代码
    目录为什么使用WebService?适用场景: 不适用场景:Axis2与CXF的区别SpringBoot使用CXF集成WebServiceWebService是一个SOA(...
    99+
    2024-04-02
  • C++ 实现高性能HTTP客户端
    目录一、什么是Http Client二、请求的过程1. 创建Http任务2. 填写header并发出3. 处理返回结果三、高性能的基本保证1. 异步调度模式2. 连接复用3. 解锁其...
    99+
    2024-04-02
  • C#实现Socket服务器及多客户端连接的方式
    服务端代码[控制台示例] static List<Socket> Sockets = new List<Socket>(); static v...
    99+
    2024-04-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作