WCF通讯例子【net.tcp;Http】方式
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Data;
namespace WCFService
{
[ServiceContract]
public interface IUser
{
[OperationContract]
DataSet GetAllUser();
[OperationContract]
bool DeleteUser(int id);
}
}
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WCFService;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace WCFServicImp
{
public class UserImp : IUser
{
private static System.Data.DataSet GetDefaultUser()
{
DataTable auto = new DataTable();
auto.Columns.Add("ID");
auto.Columns.Add("Name");
auto.Columns.Add("Age");
auto.Columns.Add("Remark");
for (int i = 1; i <= 10; i++)
{
auto.Rows.Add(new object[] { i, "用户名" + i.ToString() ,30+i,"备注"+i.ToString()});
}
DataSet ds = new DataSet();
ds.Tables.Add(auto);
return ds;
}
private static DataSet _dsUser = new DataSet();
#region IUser 成员
public DataSet GetAllUser()
{
if (_dsUser.Tables.Count == 0)
{
_dsUser = GetDefaultUser();
}
return _dsUser;
}
public bool DeleteUser(int id)
{
if (_dsUser.Tables.Count == 0)
{
return false;
}
DataTable dt = _dsUser.Tables[0];
if (dt.Rows.Count == 0)
{
return false;
}
foreach (DataRow dr in dt.Rows)
{
if (dr["ID"].ToString() == id.ToString())
{
dr.Delete();
return true;
}
}
return false;
}
#endregion
}
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel.Configuration;
using System.Configuration;
using System.ServiceModel;
using System.Reflection;
using WCFServicImp;
using WCFService;
using System.ServiceModel.Description;
private void button2_Click(object sender, EventArgs e)
{
ServiceHost host = new ServiceHost(typeof(UserImp));
host.AddServiceEndpoint(typeof(IUser),
new BasicHttpBinding(), new Uri("http://localhost:10000/TestWS"));
if (host.State != CommunicationState.Opening)
host.Open();
_hosts.Add(host);
button2.Enabled = false;
}
private void button3_Click(object sender, EventArgs e)
{
button3.Enabled = false;
string urlService = "net.tcp://localhost:10001/TestNet";
ServiceHost host = new ServiceHost(typeof(UserImp));
host.Opening += new EventHandler(host_Opening);
host.Opened += new EventHandler(host_Opened);
host.Closing += new EventHandler(host_Closing);
host.Closed += new EventHandler(host_Closed);
// The binding is where we can choose what transport layer we want to use. HTTP, TCP ect.
NetTcpBinding tcpBinding = new NetTcpBinding();
tcpBinding.TransactionFlow = false;
tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
tcpBinding.Security.Mode = SecurityMode.None; // <- Very crucial
// Add a endpoint
host.AddServiceEndpoint(typeof(IUser), tcpBinding, urlService);
// A channel to describe the service. Used with the proxy scvutil.exe tool
//ServiceMetadataBehavior metadataBehavior;
//metadataBehavior = host.Description.Behaviors.Find<ServiceMetadataBehavior>();
//if (metadataBehavior == null)
//{
// // This is how I create the proxy object that is generated via the svcutil.exe tool
// metadataBehavior = new ServiceMetadataBehavior();
// metadataBehavior.HttpGetUrl = new Uri("http://" + _ipAddress.ToString() + ":8001/MyService");
// metadataBehavior.HttpGetEnabled = true;
// metadataBehavior.ToString();
// host.Description.Behaviors.Add(metadataBehavior);
//}
host.Open();
}
void host_Opening(object sender, EventArgs e)
{
Append("Service opening ... Stand by");
}
void host_Closed(object sender, EventArgs e)
{
Append("Service closed");
}
void host_Closing(object sender, EventArgs e)
{
Append("Service closing ... stand by");
}
void host_Opened(object sender, EventArgs e)
{
}
private void Append(string str)
{
}
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel;
using System.Configuration;
using System.ServiceModel.Configuration;
using System.Reflection;
using WCFService;
private void button2_Click_1(object sender, EventArgs e)
{
string uri = "http://localhost:10000/TestWS";
object o = uteMetod<IUser>(uri, "GetAllUser");
this.dataGridView1.DataSource = (o as DataSet).Tables[0];
}
//nettcpbinding 绑定体式格式
public static object uteMethod<T>(string pUrl, string pMethodName, params object[] pParams)
{
EndpointAddress address = new EndpointAddress(pUrl);
System.ServiceModel.Channels.Binding bindinginstance = null;
NetTcpBinding ws = new NetTcpBinding();
ws.MaxReceivedMessageSize = 20971520;
ws.Security.Mode = SecurityMode.None;
bindinginstance = ws;
using (ChannelFactory<T> channel = new ChannelFactory<T>(bindinginstance, address))
{
T instance = channel.CreateChannel();
using (instance as IDisposable)
{
try
{
Type type = typeof(T);
MethodInfo mi = type.GetMethod(pMethodName);
return mi.Invoke(instance, pParams);
}
catch (TimeoutException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (CommunicationException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (Exception vErr)
{
(instance as ICommunicationObject).Abort();
throw;
}
}
}
}
/// <summary>
/// 履行办法 WSHttpBinding
/// </summary>
/// <typeparam name="T">办事接口</typeparam>
/// <param name="uri">wcf地址</param>
/// <param name="methodName">办法名</param>
/// <param name="args">参数列表</param>
public static object uteMetod<T>(string uri, string methodName, params object[] args)
{
BasicHttpBinding binding = new BasicHttpBinding(); //呈现异常:长途办事器返回错误: (415) Cannot process the message because the content type ""text/xml; charset=utf-8"" was not the expected type ""application/soap+xml; charset=utf-8"".。
//WSHttpBinding binding = new WSHttpBinding();
EndpointAddress endpoint = new EndpointAddress(uri);
using (ChannelFactory<T> channelFactory = new ChannelFactory<T>(binding, endpoint))
{
T instance = channelFactory.CreateChannel();
using (instance as IDisposable)
{
try
{
Type type = typeof(T);
MethodInfo mi = type.GetMethod(methodName);
return mi.Invoke(instance, args);
}
catch (TimeoutException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (CommunicationException)
{
(instance as ICommunicationObject).Abort();
throw;
}
catch (Exception vErr)
{
(instance as ICommunicationObject).Abort();
throw;
}
}
}
}
private void button3_Click(object sender, EventArgs e)
{
//方式一
//string endPointAddr = "net.tcp://localhost:10001/TestNet";
//NetTcpBinding tcpBinding = new NetTcpBinding();
//tcpBinding.TransactionFlow = false;
//tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
//tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
//tcpBinding.Security.Mode = SecurityMode.None;
//EndpointAddress endpointAddress = new EndpointAddress(endPointAddr);
//IUser proxy = ChannelFactory<IUser>.CreateChannel(tcpBinding, endpointAddress);
//object temp = proxy.GetAllUser();
//方式二
string uri = "net.tcp://localhost:10001/TestNet";
object o = uteMethod<IUser>(uri, "GetAllUser");
this.dataGridView1.DataSource = (o as DataSet).Tables[0];
}
private void button4_Click(object sender, EventArgs e)
{
string uri = "net.tcp://localhost:10001/TestNet";
object o = uteMethod<IUser>(uri, "DeleteUser", int.Parse((dataGridView1.SelectedRows.Count > 0 ? dataGridView1.SelectedRows[0].Cells["ID"].Value.ToString() : "0")));
MessageBox.Show(o.ToString());
button3_Click(sender, e);
}

浙公网安备 33010602011771号