using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.ServiceModel; using System.ServiceModel.Channels; using System.Threading; namespace OpcServerTest { class Program { static void Main(string[] args) { NetTcpBinding bind = new NetTcpBinding(); Uri uri = new Uri("net.tcp://127.0.0.1:4444/PLCServiceTest");//从配置文件中读取服务的Url ServiceHost host = new ServiceHost(typeof(OpcServerTest.PLCServiceTest), uri); //if中的代码可以没有,但是如果想利用Svctuil.exe生成代理类的时候,就需要下面的代码,否则将会报错,无法解析元数据 if (host.Description.Behaviors.Find() == null) { BindingElement metaElement = new TcpTransportBindingElement(); CustomBinding metaBind = new CustomBinding(metaElement); host.Description.Behaviors.Add(new System.ServiceModel.Description.ServiceMetadataBehavior()); host.AddServiceEndpoint(typeof(System.ServiceModel.Description.IMetadataExchange), metaBind, "MEX"); } host.Open(); DelegateName dn = new DelegateName(Test); AsyncCallback acb = new AsyncCallback(CallBackMethod); dn.BeginInvoke(acb, dn); Console.WriteLine("聊天室服务器开始监听: endpoint {0}", uri.ToString()); Console.WriteLine("按 ENTER 停止服务器监听..."); Console.ReadLine(); } private delegate void DelegateName(); public static void Test() { while (true) { Thread.Sleep(5000); int sum = ChatEventHelperTest.chatterstest.Count; if (sum > 0) { Random test = new Random(); int i = test.Next(sum - 1); List list = ChatEventHelperTest.chatterstest.Keys.ToList(); string a = list[i]; PLCServiceTest serviceTest = new PLCServiceTest(); string b = a + ":" + System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); serviceTest.ReturnProductCodeToMachine(b, a); Console.WriteLine(b); } } } private static void CallBackMethod(IAsyncResult ar) { } } }