最近写了一个小的东西,其中用到了WCF的REST服务,简单的分享一下,如果有不对的地方请海涵。
1:定义实体类
[Serializable]
public class ConnectService
{
private string NVSid;
public string NVSID
{
get { return NVSid; }
set { this.NVSid = value; }
}
private int port;
public int Port
{
get { return port; }
set { this.port = value; }
}
private int serviceType;
public int ServiceType
{
get { return serviceType; }
set { this.serviceType = value; }
}
private string serviceName;
public string ServiceName
{
get { return serviceName; }
set { this.serviceName = value; }
}
private string connectDateTime;
public string ConnectDateTime
{
get { return connectDateTime; }
set { this.connectDateTime = value; }
}
private int state;
public int State
{
get { return state; }
set { this.state = value; }
}
private string desc;
public string Desc
{
get { return desc; }
set { this.desc = value; }
}
}
2: 定义服务端接口,传动模式为POST的模式
[ServiceContract]
public interface ICommandDispatchService
{
[OperationContract]
[WebInvoke(UriTemplate = "keepHeartJump", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void KeepHeartJump(ConnectService connectService);
[OperationContract]
[WebInvoke(UriTemplate = "registConnectService", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void RegistConnectService(ConnectService connectService);
[OperationContract]
[WebInvoke(UriTemplate = "cannelConnectService", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void CannelConnectService(ConnectService connectService);
}
[ServiceContract]
public interface ICommandHandleMsgService
{
//同步设备信息
[OperationContract]
[WebInvoke(UriTemplate = "syncDeviceInfo", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void SyncDeviceInfo(List<Device> devices);
//同步联动信息
[OperationContract]
[WebInvoke(UriTemplate = "syncAutomation", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void SyncAutomation();
//发送文本消息
[OperationContract]
[WebInvoke(UriTemplate = "sendTextMsg", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void SendTextMsg(Communication communication);
//发送图片消息
[OperationContract]
[WebInvoke(UriTemplate = "sendPicMsg", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void SendPicMsg(Communication communication);
//发送报警消息(联动方案用)
[OperationContract]
[WebInvoke(UriTemplate = "startAlarmMsg", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void StartAlarmMsg(Communication communication);
//发送联动报警图片消息
[OperationContract]
[WebInvoke(UriTemplate = "sendAlarmPic", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void SendAlarmPic(Communication communication);
//设备是否上线,下线
[OperationContract]
[WebInvoke(UriTemplate = "deviceShankLine", Method = "POST", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
void DeviceShankLine(Device device);
}
3:定义用于客户端通讯的接口
public interface IHandleMsg
{
//同步设备信息
void SyncDeviceInfo(List<Device> devices);
//同步联动信息
void SyncAutomation();
//发送文本消息
void SendTextMsg(Communication communication);
//发送图片消息
void SendPicMsg(Communication communication);
//发送报警消息(联动方案用)
void StartAlarmMsg(Communication communication);
//发送联动报警图片消息
void SendAlarmPic(Communication communication);
//设备是否上线,下线
void DeviceShankLine(Device device);
}
public interface IReisterService
{
void KeepHeartJump(ConnectService connectService);
void RegistConnectService(ConnectService connectService);
void CannelConnectService(ConnectService connectService);
}
4:注册,绑定,启动等用户接口控件
[Serializable]
public class ReisterService : ICommandDispatchService
{
public void KeepHeartJump(ConnectService connectService)
{
CommandDispatchServiceManager.Singleton.KeepHeartJump(connectService);
}
public void RegistConnectService(ConnectService connectService)
{
CommandDispatchServiceManager.Singleton.RegistConnectService(connectService);
}
public void CannelConnectService(ConnectService connectService)
{
CommandDispatchServiceManager.Singleton.CannelConnectService(connectService);
}
}
public class CommandDispatchServiceManager : IDisposable
{
private static CommandDispatchServiceManager commandDispatchServiceManager = new CommandDispatchServiceManager();
private static object objectLock = new object();
private CommandDispatchServiceManager()
{
}
//private ServiceHost serviceHost = null;
private WebServiceHost serviceHost = null;
/// <summary>
/// 启动一个监听服务。
/// </summary>
/// <param name="ucShiJianDiaoDu"></param>
/// <returns></returns>
public void StartService()
{
if (!this.started)
{
lock (objectLock)
{
if (!this.started)
{
monitorAddress = Helper.GetMonitorAddress();
monitorPort = Helper.GetMonitorPoint(0);
Uri baseAddress = new Uri(string.Format("http://{0}:{1}/", monitorAddress, monitorPort));
serviceHost = new WebServiceHost(typeof(ReisterService), baseAddress);
WebHttpBinding binding = new WebHttpBinding(WebHttpSecurityMode.None);
XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
readerQuotas.MaxArrayLength = 2147483647;
readerQuotas.MaxStringContentLength = 2147483647;
readerQuotas.MaxBytesPerRead = 2147483647;
binding.ReaderQuotas = readerQuotas;
binding.MaxReceivedMessageSize = 2147483647;
binding.MaxBufferPoolSize = 2147483647;
binding.MaxBufferSize = 2147483647;
try
{
serviceHost.AddServiceEndpoint(typeof(ICommandDispatchService), binding, string.Format("http://{0}:{1}/",
monitorAddress, monitorPort));
serviceHost.Open();
}
catch (Exception exp)
{
BestelException.WriteLog("StartService", exp);
}
this.started = true;
}
}
}
}
public string monitorAddress = "";
public string monitorPort = "";
public void RegisterTriggerControl(IReisterService triggerAlarmControl)
{
triggerAlarmControls.Add(triggerAlarmControl);
}
public void CancelTriggerControl(IReisterService triggerAlarmControl)
{
triggerAlarmControls.Remove(triggerAlarmControl);
}
public void KeepHeartJumpControl(IReisterService triggerAlarmControl)
{
triggerAlarmControls.Add(triggerAlarmControl);
}
public void StopService()
{
try
{
serviceHost.Close();
if (this.started)
{
lock (objectLock)
{
if (this.started)
{
this.started = false;
}
}
}
}
catch (Exception exp)
{
BestelException.WriteLog("停止报警服务--StopService", exp.ToString());
}
}
//<summary>
//推送WIN8绘制的数据
//</summary>
//<param name="pushmsg"></param>
public void KeepHeartJump(ConnectService connectService)
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork -= (sender, e) => { };
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].KeepHeartJump(connectService);
}
};
backgroundWorker.RunWorkerAsync();
}
public void RegistConnectService(ConnectService connectService)
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].RegistConnectService(connectService);
}
};
backgroundWorker.RunWorkerAsync();
}
}
public void CannelConnectService(ConnectService connectService)
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork -= (sender, e) => { };
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].CannelConnectService(connectService);
}
};
backgroundWorker.RunWorkerAsync();
}
}
private List<IReisterService> triggerAlarmControls = new List<IReisterService>();
public static CommandDispatchServiceManager Singleton
{
get { return commandDispatchServiceManager; }
}
private bool started = false;
public void Dispose()
{
if (this.triggerAlarmControls != null && this.triggerAlarmControls.Count > 0)
{
this.triggerAlarmControls.Clear();
}
if (serviceHost != null) serviceHost.Close();
}
}
[Serializable]
public class HandleService :ICommandHandleMsgService
{
public void SyncDeviceInfo(List<Device> devices)
{
CommandHandleMsgerviceManager.Singleton.SyncDeviceInfo(devices);
}
public void SyncAutomation()
{
CommandHandleMsgerviceManager.Singleton.SyncAutomation();
}
public void SendTextMsg(Communication communication)
{
CommandHandleMsgerviceManager.Singleton.SendTextMsg(communication);
}
public void SendPicMsg(Communication communication)
{
CommandHandleMsgerviceManager.Singleton.SendPicMsg(communication);
}
public void StartAlarmMsg(Communication communication)
{
CommandHandleMsgerviceManager.Singleton.StartAlarmMsg(communication);
}
public void SendAlarmPic(Communication communication)
{
CommandHandleMsgerviceManager.Singleton.SendAlarmPic(communication);
}
public void DeviceShankLine(Device device)
{
CommandHandleMsgerviceManager.Singleton.DeviceShankLine(device);
}
}
public class CommandHandleMsgerviceManager : IDisposable
{
private static CommandHandleMsgerviceManager commandDispatchServiceManager = new CommandHandleMsgerviceManager();
private static object objectLock = new object();
private CommandHandleMsgerviceManager()
{
}
//private ServiceHost serviceHost = null;
private WebServiceHost serviceHost = null;
/// <summary>
/// 启动一个监听服务。
/// </summary>
/// <param name="ucShiJianDiaoDu"></param>
/// <returns></returns>
public void StartService()
{
if (!this.started)
{
lock (objectLock)
{
if (!this.started)
{
monitorAddress = Helper.GetHandleAddress();
monitorPort = Helper.GetHandlerPoint(0);
Uri baseAddress = new Uri(string.Format("http://{0}:{1}/", monitorAddress, monitorPort));
serviceHost = new WebServiceHost(typeof(HandleService), baseAddress);
WebHttpBinding binding = new WebHttpBinding(WebHttpSecurityMode.None);
XmlDictionaryReaderQuotas readerQuotas = new XmlDictionaryReaderQuotas();
readerQuotas.MaxArrayLength = 2147483647;
readerQuotas.MaxStringContentLength = 2147483647;
readerQuotas.MaxBytesPerRead = 2147483647;
binding.ReaderQuotas = readerQuotas;
binding.MaxReceivedMessageSize = 2147483647;
binding.MaxBufferPoolSize = 2147483647;
binding.MaxBufferSize = 2147483647;
try
{
serviceHost.AddServiceEndpoint(typeof(ICommandHandleMsgService), binding, string.Format("http://{0}:{1}/",
monitorAddress, monitorPort));
serviceHost.Open();
}
catch (Exception exp)
{
BestelException.WriteLog("StartService", exp);
}
this.started = true;
}
}
}
}
public string monitorAddress = "";
public string monitorPort = "";
public void RegisterTriggerControl(IHandleMsg triggerAlarmControl)
{
triggerAlarmControls.Add(triggerAlarmControl);
}
public void CancelTriggerControl(IHandleMsg triggerAlarmControl)
{
triggerAlarmControls.Remove(triggerAlarmControl);
}
public void KeepHeartJumpControl(IHandleMsg triggerAlarmControl)
{
triggerAlarmControls.Add(triggerAlarmControl);
}
public void StopService()
{
try
{
serviceHost.Close();
if (this.started)
{
lock (objectLock)
{
if (this.started)
{
this.started = false;
}
}
}
}
catch (Exception exp)
{
BestelException.WriteLog("停止报警服务--StopService", exp.ToString());
}
}
public void SyncDeviceInfo(List<Device> device)
{
BackgroundWorker backgroundWorker = new BackgroundWorker();
backgroundWorker.DoWork -= (sender, e) => { };
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].SyncDeviceInfo(device);
}
};
backgroundWorker.RunWorkerAsync();
}
public void SyncAutomation()
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].SyncAutomation();
}
};
backgroundWorker.RunWorkerAsync();
}
}
public void SendTextMsg(Communication connectService)
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork -= (sender, e) => { };
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].SendTextMsg(connectService);
}
};
backgroundWorker.RunWorkerAsync();
}
}
public void SendPicMsg(Communication connectService)
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork -= (sender, e) => { };
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].SendPicMsg(connectService);
}
};
backgroundWorker.RunWorkerAsync();
}
}
public void StartAlarmMsg(Communication connectService)
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork -= (sender, e) => { };
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].StartAlarmMsg(connectService);
}
};
backgroundWorker.RunWorkerAsync();
}
}
public void SendAlarmPic(Communication connectService)
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork -= (sender, e) => { };
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].SendAlarmPic(connectService);
}
};
backgroundWorker.RunWorkerAsync();
}
}
public void DeviceShankLine(Device connectService)
{
using (BackgroundWorker backgroundWorker = new BackgroundWorker())
{
backgroundWorker.DoWork -= (sender, e) => { };
backgroundWorker.DoWork += (sender, e) =>
{
for (int i = 0; i < triggerAlarmControls.Count; i++)
{
if (triggerAlarmControls[i] != null)
triggerAlarmControls[i].DeviceShankLine(connectService);
}
};
backgroundWorker.RunWorkerAsync();
}
}
private List<IHandleMsg> triggerAlarmControls = new List<IHandleMsg>();
public static CommandHandleMsgerviceManager Singleton
{
get { return commandDispatchServiceManager; }
}
private bool started = false;
public void Dispose()
{
if (this.triggerAlarmControls != null && this.triggerAlarmControls.Count > 0)
{
this.triggerAlarmControls.Clear();
}
if (serviceHost != null) serviceHost.Close();
}
}
5:客户端调用与相互通信
public partial class Form1 : Form, IReisterService, IHandleMsg
{
实现接口
}
6:调用服务REST服务的POST方式
WebChannelFactory<WCFServiceClibs.ICommandDispatchService> scf = new WebChannelFactory<ICommandDispatchService>(new Uri(System.Configuration.ConfigurationSettings.AppSettings["URL"]));
WCFServiceClibs.ICommandDispatchService svc = scf.CreateChannel();
svc.RegistConnectService(connection);