WCF基本实现(Server和Client)

Windows Communication Foundation(WCF)是由微软开发的一系列支持数据通信的应用程序框架,可以很多传输协议与WCF服务进行通信。常见的5个协议有:
(1)HTTP:允许与WCF服务通信,可使用HTTP通信技术创建WCF Web服务。
(2)TCP:可以通过TCP协议与WCF服务通信,效率较高。
(3)UDP:采用UDP协议与WCF服务通信。
(4)命名管道:该WCF服务与调用代码位于同一台计算机的不同进程上。
(5)MSMQ:一种排队技术,允许应用同程序发送的小心通过队列路由到目的地。
在常见的应用中HTTP和TCP应用较为普遍,WCF大大降低了编程难度,但是WCF配置一直是一大难点。构建一个WCF程序通常分为三个部分:服务类(Server)、宿主(Host)、客户程序(Client)。为了让Server和Client可以顺利通信,双方应该根据契约定义相关的操作和数据。例如客户端要向服务端请求获取相关的学生信息,此时我们可以先定义学生的数据结构,其具体如下:

 [DataContract]
   public class StudentInfo
    {
        [DataMember]
        public string Name { get; set; }
        [DataMember]
        public int StudentID { get; set; }
        [DataMember]
        public string University { get; set; }
    }
此时我们应该定义相关操作契约接口,其具体如下:
   [ServiceContract]
    public interface IStudentContract
    {
        [OperationContract]   //操作约定
        StudentInfo GetStudentInfo();
    }
此时已经成功定义好了数据结构和相关的操作协定,Server端应该实现IStudentContract接口,然后Client可以向Server发送请求获取相关学生信息,其Server端的详细实现如下:
  public class StudentDataService : IStudentContract
    {

        public StudentInfo GetStudentInfo()
        {
            StudentInfo info = new StudentInfo() 
            { Name = "Mike", StudentID = 100, University = "HUST" };
            return info;
        }
    }

至此服务Server端已经实现了其契约相关接口,接下来需要将Server寄宿到相关程序(window服务、exe可执行程序或者IIS等)。为了简化处理,采用寄宿到控制台里,相关代码如下:

 static void Main(string[] args)
        {
            ServiceHost host = new ServiceHost(typeof(StudentDataService ));
            host.Open();
            Console.WriteLine("正在监听:" );
            Console.ReadKey();
        }

此时应该在此控制台的配置文件App.config里面添加如下配置,详细如下:

 <system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="NewBinding0" openTimeout="00:30:00" receiveTimeout="00:30:00" sendTimeout="00:30:00" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
          <security mode="None"/>
        </binding>
      </netTcpBinding>
    </bindings>
    <behaviors>
      <serviceBehaviors>
        <behavior name="myBehavior">
          <serviceMetadata httpGetEnabled="False"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>

    <services>
      <service name="StudentDataService" //注意添加上命名空间 behaviorConfiguration="myBehavior">
        <endpoint address="net.tcp://localhost:8126/StudentDataService" binding="netTcpBinding" bindingConfiguration="NewBinding0" contract="IStudentContract"/>  //注意添加上命名控件
      </service>
    </services>
  </system.serviceModel>

为了测试相关功能是否正常,Client测试的相关代码如下:

static void Main(string[] args)
        {
        var factory = new ChannelFactory<IStudentContract>("TestStudentClient");  //此名名保持和配置文件中一致
            IStudentContract_channel = factory.CreateChannel();
            while (true)
            {
                StudentInfo info = _channel.GetStudentInfo();
                Console.WriteLine("姓名:" + info.Name);
                Console.WriteLine("学号:" + info.StudentID);
                Console.WriteLine("学校:" + info.University);
                Thread.Sleep(10000);
            }
            Console.ReadKey();
        }

相关配置如下:

<system.serviceModel>
    <bindings>
      <netTcpBinding>
        <binding name="NewBinding0" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
          <security mode="None"/>
        </binding>
      </netTcpBinding>
    </bindings>
    <client>
      <endpoint address="net.tcp://localhost:8126/TextDataService" binding="netTcpBinding" bindingConfiguration="NewBinding0" contract="IStudentContract" name="TestStudentClient" kind="" endpointConfiguration=""/>
    </client>
  </system.serviceModel>

至此服务Server和Client的代码基本完成。本文主要是采用netTcp方式进行WCF通信,经过测试Client可以从Server获取到相关数据。

WCF(Windows Communication Foundation)和HTTP(Hypertext Transfer Protocol)都可以用于文件传输,它们各有优缺点,下面我们来分别介绍一下。 WCF文件传输实验: 1. 创建一个WCF服务 在Visual Studio创建一个WCF服务,可以选择“WCF Service Application”模板或“WCF Service Library”模板。这里我们选择“WCF Service Application”模板,创建一个名为“FileTransferService”的服务。 2. 添加文件传输方法 在服务添加一个文件传输方法,可以定义一个接口,如下所示: ``` [ServiceContract] public interface IFileTransferService { [OperationContract] void UploadFile(FileTransferData data); } ``` 其,FileTransferData是一个包含文件名和文件内容的数据传输对象(DTO)。 3. 实现文件传输方法 在服务实现文件传输方法,可以使用以下代码: ``` public void UploadFile(FileTransferData data) { string filePath = Path.Combine(@"D:\Files\", data.FileName); using (FileStream fs = new FileStream(filePath, FileMode.Create)) { fs.Write(data.FileContents, 0, data.FileContents.Length); } } ``` 其,将文件保存在D:\Files\目录下。 4. 测试文件传输方法 可以使用WCF Test Client或编写客户端应用程序来测试文件传输方法。 HTTP文件传输实验: 1. 创建一个Web应用程序 在Visual Studio创建一个Web应用程序,选择“ASP.NET Web Application”模板或“ASP.NET Empty Web Application”模板。这里我们选择“ASP.NET Web Application”模板,创建一个名为“FileTransferWeb”的Web应用程序。 2. 添加文件上传页面 在Web应用程序添加一个文件上传页面,可以使用以下代码: ``` <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Upload.aspx.cs" Inherits="FileTransferWeb.Upload" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <input type="file" name="file" id="file" /> <input type="button" value="Upload" onclick="uploadFile()" /> <br /><br /> <div id="result"></div> </div> </form> <script src="Scripts/jquery-1.10.2.min.js"></script> <script type="text/javascript"> function uploadFile() { var file = document.getElementById("file").files[0]; var formData = new FormData(); formData.append("file", file); $.ajax({ url: "UploadHandler.ashx", type: "POST", data: formData, processData: false, contentType: false, success: function (result) { $("#result").html(result); }, error: function (err) { $("#result").html(err.responseText); } }); } </script> </body> </html> ``` 其,使用AJAX上传文件,将文件上传到“UploadHandler.ashx”处理程序。 3. 添加文件上传处理程序 在Web应用程序添加一个文件上传处理程序,可以使用以下代码: ``` <%@ WebHandler Language="C#" Class="UploadHandler" %> using System; using System.IO; using System.Web; public class UploadHandler : IHttpHandler { public void ProcessRequest(HttpContext context) { HttpPostedFile file = context.Request.Files["file"]; string filePath = Path.Combine(@"D:\Files\", file.FileName); file.SaveAs(filePath); context.Response.Write("File uploaded successfully"); } public bool IsReusable { get { return false; } } } ``` 其,将文件保存在D:\Files\目录下。 4. 测试文件上传页面 启动Web应用程序,访问上传页面,选择一个文件并上传。 以上就是WCF和HTTP文件传输实验的基本步骤,可以根据实际需求进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值