一、WCF概念:
Windows Communication Foundation(WCF)的一切都与服务(Service)有关。WCF用于创建服务、为服务提供宿主、使用服务,并确保相关服务的安全性;WCF用于实现标准和互操作性;WCF还能够有效的提高开发效率;简而言之,WCF使得分布式计算对于专业软件开发人员变得触手可及。
首先,服务是能够为用户提供各种功能的一组端点;端点是网络上的一个可以被发送消息的资源,用户通过向端点发送消息来使用服务提供的功能;发送的消息格式要必须符合客户端和服务一致认可的契约;服务将在端点中指定的地址上进行监听,并要求接收到的消息符合特定的格式要求。图1.1显示了客户端和服务之间基本关系。
图1.1 客户端和服务之间的通讯过程
对于客户端来说,要完成与服务之间的有效信息通讯,必须了解所谓的“ABC”,即:地址(Address)、绑定(Binding),以及契约(Contract)。
1. "A"用于表示地址,描述Where信息。地址定义了网络消息应该发送到什么地方,端点将在哪里接收消息;客户端必须将消息发送到地址指定的位置。
2. "B"用于表示绑定,描述How信息。绑定定义了端点用于通讯的信道。信道是WCF应用程序中所有消息的传输管道。一个信道由一系列的绑定元素组成。
3. "C"用于表示契约,描述What信息。契约用于定义由端点提供的功能,或是特性集。契约定义了一个端点向外暴露的各种操作和操作所需要的消息格式。契约操作完成了端点实现类中各种方法的映射,包括:函数签名、输入参数,以及返回值。
注:服务端与客户端之间传输信息,三要素"ABC"是必不可少的。
二、a sample for WCF
这是我的第一篇博客,如有不托的地方,欢迎大家提出建议,谢谢!
实现流程:在Service端取keywords,将keywords传给client端,再由client端通过API搜索到url地址,将其存入数据库中,并返回当前keyword的搜索状态(即成功与否)。
首先,需要建立两个projects,一个是client端,一个是Service端。为了能在本机上测试到程序的运行结果,可在本地数据库中同时创建service与client的库。
1.serve-side:
在service库中建立一张表,用于存储keyword与keyword的搜索状态。
下面是代码实现:
serve-side
using System.ServiceModel;
using System.Configuration;
using System.Data.SqlClient;
using System.IO;
using System.Collections.Generic;
namespace EssentialWCF
{
//In the service-side,the interface defines a service contract,and the methods define an operation contract.
[ServiceContract]
public interface IKeywordService
{
[OperationContract]
//Indicates that take keywords.
List<string> GetKeyword();
[OperationContract]
//Indicates that the search state for the keyword.
void SuccessResult(string _keyword);
}
public class KeywordService : IKeywordService
{
public string ConnStr = ConfigurationManager.AppSettings["ConnectionString"];
public List<string> GetKeyword()
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
List<string> list = new List<string>();
string Sqlstr = "select top 3 keyword from KeywordList";
SqlCommand cmd = new SqlCommand(Sqlstr, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
//It read the selected field values from the database.
while (reader.Read())
{
list.Add(reader[0].ToString());
}
return list;
}
}
public void SuccessResult(string _keyword)
{
using (SqlConnection conn = new SqlConnection(ConnStr))
{
//Success for searching the URL address of the keyword,then return "1".
string sqlStr = string.Format("update KeywordList SET ProcessResult=1 where keyword='{0}'", _keyword);
SqlCommand cmd = new SqlCommand(sqlStr, conn);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
//implementation the WCF for the service
public class Service
{
public static void Main()
{
ServiceHost serviceHost = new ServiceHost(typeof(KeywordService),
new Uri("http://localhost:8000/EssentialWCF"));
//Uri[] uri = new Uri[1] { new Uri("http://localhost:8000/EssentialWCF") };
//ServiceHost serviceHost1 = new ServiceHost(typeof(KeywordService), uri);
//BasicHttpBinding basichttpbinding = new BasicHttpBinding();
//serviceHost.AddServiceEndpoint(typeof(IKeywordService),basichttpbinding,"");
serviceHost.AddServiceEndpoint(typeof(IKeywordService), new BasicHttpBinding(), "");
serviceHost.Open();
Console.WriteLine("Press <Enter> to terminate.\n\n");
Console.ReadLine();
serviceHost.Close();
}
}
}
2.Client-side
client-side
using System.ServiceModel;
using System.Collections.Generic;
using System.Configuration;
using System.Net;
using System.IO;
using System.Xml;
using System.Data.SqlClient;
using System.Data;
using System.Threading;
using System.Threading.Tasks;
namespace Client
{
[ServiceContract]
public interface IKeywordService
{
[OperationContract]
List<string> GetKeyword();
[OperationContract]
void SuccessResult(string _keyword);
}
class Client
{
public static string Connstr = ConfigurationManager.AppSettings["ConnString"];
public delegate string[] KeywordsUrl(string keyword);
static void Main()
{
//create channel that client and serve communicate.
ChannelFactory<IKeywordService> myChannelFactory =
new ChannelFactory<IKeywordService>(
new BasicHttpBinding(),
new EndpointAddress
("http://localhost:8000/EssentialWCF"));
using (SqlConnection conn = new SqlConnection(Connstr))
{
try
{
//implement to creat links with serve-side.
IKeywordService wcfClient = myChannelFactory.CreateChannel();
List<string> keywords = wcfClient.GetKeyword();
Url url = new Url();
string sql = "";
conn.Open();
List<Task<Num>> tasks = new List<Task<Num>>();
foreach (string keyword in keywords)
{
//implement multithreading
Task<Num> task = new Task<Num>(((object par1) =>
{
string kw = par1 as string;
Num UrlKeyword = new Num();
UrlKeyword.Url = url.RequestUrl(kw);
UrlKeyword.Keyword = kw;
return UrlKeyword;
}), keyword);
task.Start();
tasks.Add(task);
}
//wait all the tasks to be executed finishing.
Task.WaitAll(tasks.ToArray());
foreach (var task in tasks)
{
string[] urls = task.Result.Url;
string keyword = task.Result.Keyword;
//the URL address and keyword insert into the client library.
foreach (string SingleUrl in urls)
{
sql = string.Format("insert into Client (URL,KeyWord) values('{0}','{1}')", SingleUrl, keyword);
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.ExecuteNonQuery();
}
wcfClient.SuccessResult(keyword);
}
}
catch (Exception)
{
}
finally
{
myChannelFactory.Close();
}
}
}
}
//declare a Num class that include URL and keyword properties.
class Num
{
private string[] url;
private string keyword;
public string[] Url
{
set { url = value; }
get { return url; }
}
public string Keyword
{
set { keyword = value; }
get { return keyword; }
}
}
class Url
{
//request a URL address,and gain the string that serve returned.
public string[] RequestUrl(string keyword)
{
string url = string.Format("http://api.myspace.com/opensearch/videos?searchTerms='{0}'&format=xml", keyword);
string strURL = string.Empty;
string[] result;
int i = 0;
HttpWebRequest request = null;
request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
strURL = reader.ReadToEnd().ToString();
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml(strURL);
XmlNodeList xmlList = xmlDoc.GetElementsByTagName("videoUrl");
result = new string[xmlList.Count];
foreach (XmlNode xmlNode in xmlList)
{
result[i] = xmlNode.InnerText;
i++;
}
return result;
}
}
}
}
如有错误,欢迎大家指出,谢谢!

浙公网安备 33010602011771号