用C#基于WCF创建TCP的Service供Client端调用

本文将详细讲解用C#基于WCF创建TCP的Service供Client端调用的详细过程

1):首先创建一个Windows
Service的工程

2):生成的代码工程结构如下所示

3):我们将Service1改名为MainService

4):
添加一个Interface来定义Service的契约

4.1):截图如下所示

4.2):IOrderService.cs的代码如下所示

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;

namespace EricSunService
{
[ServiceContract]
interface IOrderService
{
[OperationContract]
[FaultContract(typeof(ServiceFault))]
AccountLoginResponse AccountLogin(AccountLoginRequest request);

[OperationContract]
[FaultContract(typeof(ServiceFault))]
AccountTopUpResponse AccountTopUp(AccountTopUpRequest request);
}

[DataContract]
public class ServiceFault
{
[DataMember]
public string CorrelationId { get; set; }
[DataMember]
public string Message { get; set; }
[DataMember]
public string Address { get; set; }
}
}

5):然后添加其他的类实现对应的Service,并且实现对Service的Host

5.1):最终的代码工程截图如下所示(这里的EricSunData工程是用于数据类型的定义,为了更好的逻辑结构分层,这里我们主要以AccountLogin.cs中所实现的OrderService进行讲解)

5.2):AccountLogin.cs的代码如下所示(实现IOrderService中的部分接口)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;

namespace EricSunService
{
public partial class OrderService : IOrderService
{
public AccountLoginResponse AccountLogin(AccountLoginRequest request)
{
// do some logic with account info
AccountLoginResponse loginResponse = new AccountLoginResponse() { AccountBalance = 10000000.00, Status = new AccountLoginStatus() };
return loginResponse;
}
}

[DataContract]
public class AccountLoginRequest
{
[DataMember]
public string Name { get; set; }
[DataMember]
public string Password { get; set; }
}

[DataContract]
public class AccountLoginResponse
{
[DataMember]
public double AccountBalance { get; set; }
[DataMember]
public AccountLoginStatus Status { get; set; }
}

public enum AccountLoginStatus
{
NoError = 0,
InvalidAccountInfo // Invalid Account Info
}
}

5.3):MainService的代码如下所示 (进行对Service的Host)

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace EricSunService
{
public partial class MainService : ServiceBase
{
private ServiceHost _orderService;

public MainService()
{
InitializeComponent();
}

protected override void OnStart(string[] args)
{
_orderService = new ServiceHost(typeof(OrderService));
_orderService.Open();
}

protected override void OnStop()
{
_orderService.Close();
}
}
}

5.4):Program.cs的代码如下所示 (.exe运行时主入口)

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace EricSunService
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
static void Main()
{
#if DEBUG
ServiceHost host = new ServiceHost(typeof(OrderService));
host.Open();
System.Threading.Thread.Sleep(System.Threading.Timeout.Infinite);
#else
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new MainService()
};
ServiceBase.Run(ServicesToRun);
#endif
}
}
}

6):运行Service时的可能错误以及App.config的配置

6.1):当我们build真个solution之后,到对应的debug目录去运行对应的EricSunService.exe文件时,有可能会出现如下错误,为了解决如下的错误才有了5.4中写法

6.2):App.config文件的配置信息,是对WCF框架下暴露Service的endpoint(ABC)的一个详细配置

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>

<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="OrderServiceBehavior">
<serviceMetadata httpGetEnabled="false" />
<serviceDebug />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service behaviorConfiguration="OrderServiceBehavior" name="EricSunService.OrderService">
<host>
<baseAddresses>
<add baseAddress="net.tcp://localhost:3434/" />
</baseAddresses>
</host>
<endpoint address="" binding="netTcpBinding" bindingConfiguration="NetTcpBindingConfig" contract="EricSunService.IOrderService"/>
<endpoint address="mex" binding="mexTcpBinding" bindingConfiguration="" contract="IMetadataExchange" />
</service>
</services>
<bindings>
<netTcpBinding>
<binding name="NetTcpBindingConfig">
<security mode="None" />
</binding>
</netTcpBinding>
</bindings>
</system.serviceModel>

</configuration>

7):创建一个Asp.Net MVC
的工程作为Client端去调用所提供的Service,之后是添加对OrderService的引用,如下图所示

8):在EricSunService.exe运行起来的状态下,去update此OrderServiceReference,如下图所示

9):点击Show All
Files之后会看到如下详细的工程文件信息

10):同时我们发现了如下图的错误信息

11):为了解决这个错误信息,请按下图的步骤进行操作

11.1):鼠标右键点击OrderServiceReference后选择Config Service Reference

11.2):取消对Reuse types in referenced assemblies的勾选

11.3):点击上图中的OK按钮之后,生成了Service所对应Data的详细信息,如下图所示

11.4):最终的工程结构如下图所示

12):Service的引用添加完毕之后,就可以对Service进行调用了,我们这里选择的是ChannelFactory的方式,详细代码如下所示

12.1):OrderServiceClientFactory.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Web;
using EricSunWeb.OrderServiceReference;

namespace EricSunWeb.Business
{
public static class OrderServiceClientFactory
{
private static readonly object CRITICAL_SECTION = new object();
private static ChannelFactory<IOrderServiceChannel> s_ChannelFactory = null;

public static IOrderServiceChannel CreateClient()
{
if (s_ChannelFactory == null || s_ChannelFactory.State == CommunicationState.Faulted)
{
lock (CRITICAL_SECTION)
{
if (s_ChannelFactory == null)
{
s_ChannelFactory = new ChannelFactory<IOrderServiceChannel>("NetTcpBinding_IOrderService");
}
else if (s_ChannelFactory.State == CommunicationState.Faulted)
{
s_ChannelFactory.Abort();
s_ChannelFactory = new ChannelFactory<IOrderServiceChannel>("NetTcpBinding_IOrderService");
}
}
}

return s_ChannelFactory.CreateChannel();
}
}
}

12.2):OrderManager.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using EricSunWeb.OrderServiceReference;

namespace EricSunWeb.Business
{
public class OrderManager
{
public void AccountLogin(string name, string password)
{
var request = new AccountLoginRequest
{
Name = name,
Password = password
};

AccountLoginResponse response = null;
var client = OrderServiceClientFactory.CreateClient();
response = client.AccountLogin(request);

if (response.Status == AccountLoginStatus.NoError)
{

}
else
{

}
}
}
}

12.3):OrderController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using EricSunWeb.Business;
using EricSunWeb.OrderServiceReference;

namespace EricSunWeb.Controllers
{
public class OrderController : Controller
{
//
// GET: /Order/

public ActionResult Index()
{
new OrderManager().AccountLogin("EricSun", "password");
return View();
}

}
}

OK,整个过程就这样结束了。

用C#基于WCF创建TCP的Service供Client端调用

时间: 2024-08-07 22:44:26

用C#基于WCF创建TCP的Service供Client端调用的相关文章

Learning WCF Chapter1 Generating a Service and Client Proxy

In the previous lab,you created a service and client from scratch without leveraging the tools available to WCF developers. Although this helps you to understand the raw requirements for sending messages between clients and services,in reality,develo

网络编程-TCP程序实例(client端heserver端相互通信)

1 package com.yyq; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.OutputStream; 6 import java.net.InetAddress; 7 import java.net.Socket; 8 9 10 /* 11 * 演示tcp的传输的客户端和服务端的互访 12 * 需求:客户端给服务端发送数据服务端获取信息后给客户端回送数据 13 */ 14 /

使用WCF 创建 Rest service

REST SERVICE 允许客户端修改url路径,并且web端功过url 请求数据. 他使用http协议进行通讯,想必大家都知道 . 并且我们可以通过设置进行数据类型转换, 支持XML,JSON 格式. 大多情况下我们都采用webservice ,或在MVC下创建REST服务来支持服务端调用. 但WCF当道之时.我们是否想过我们还有一大把的wcf服务想采用REST json格式来进行手机模块接口调用呢? 下面介绍通过WCF创建REST serveic ,你无需改变原有服务处理,只需要添加一些配

WCF、WebAPI、WCF REST、Web Service之间的区别

在.net平台下,有大量的技术让你创建一个HTTP服务,像Web Service,WCF,现在又出了Web API.在.net平台下,你有很多的选择来构建一个HTTP Services.我分享一下我对Web Service.WCF以及Web API的看法. Web Service 1.它是基于SOAP协议的,数据格式是XML 2.只支持HTTP协议 3.它不是开源的,但可以被任意一个了解XML的人使用 4.它只能部署在IIS上 WCF 1.这个也是基于SOAP的,数据格式是XML 2.这个是We

基于.Net FrameWork的 RestFul Service

关于本文 这篇文章的目的就是向大家阐述如何在.net framework 4.0中创建RestFul Service并且使用它. 什么是web Services,什么是WCF 首先讲到的是web Service, 它是一种能够让客户端程序在web页面上通过HTTP协议请求需要数据的部件.我们可以用Asp.net创建普通的Web Services并且让这些Services能够被客户端程序所调用. 其次说到的是Web Services,它是一个编程平台,它能够通过遵循Simple Object Ac

wcf 创建

WCF 作为可跨域 跨应用的服务工具会经常用到的地方很多,也会出现各种蛋疼的问题,以下是本人在使用WCF中所遇到的各种问题,最多遇到的就是部署iis上时候问题.希望能帮助到各位. 长话短说,简单的契约 contract 和service 创建我就不说了 ,直接说wcf创建, 一首先谈服务创建(有经验的可以略过观看此步骤):当我们创建一个可运行成功的svc文件时 就标志的我们的服务创建成功. 1.那么怎么创建一个svc文件,直接点击项目右键新建,找到wcf服务,这个文件的后缀就是.svc文件. 2

基于Socket创建Web服务

基于Socket创建Web服务 为什么要使用Socket呢,我们来看下图 Socket原理图回顾: -------------------编写SocketService,完成字母小写转大写功能----------------------------- ServerSocket服务器端代码如下: public static void main(String[] args) throws IOException { // 1:建立服务器端的tcp socket服务,必须监听一个端口 ServerSo

怎样创建.NET Web Service http://blog.csdn.net/xiaoxiaohai123/article/details/1546941

为什么需要Web Service 在通过internet网购买商品后,你可能对配送方式感到迷惑不解.经常的情况是因配送问题找配送公司而消耗你的大量时间,对于配送公司而言这也不是一项增值服务. 为了解决这种问题,配送公司需要在不降低安全级别的情况下了解更多的递送信息,然而安全公司设计的安全系统却非常复杂.那么我们能不能只使用80端口(web服务器端口)并且只通过web服务器提供信息呢?所以,我们建立了一个全新的web应用程序以便从核心商业应用程序中获得数据.配送公司将为些东西付money,所有的公

使用Java创建RESTful Web Service(转)

REST是REpresentational State Transfer的缩写(一般中文翻译为表述性状态转移).2000年Roy Fielding博士在他的博士论文“Architectural Styles and the Design of Network-based Software Architectures”<体系结构与基于网络的软件架构设计>中提出了REST. REST是一种体系结构.而HTTP是一种包含了REST架构属性的协议. REST基础概念 在REST中所有东西都被看作资源.