WCF服务端与客户端代码示例

近日在研究WCF,现将成功过的代码贴出来。

一、服务端代码:

                Uri wcfUri = new Uri("http://10.68.198.41:8001/WCF/");
                ServiceHost serviceHost = new ServiceHost(typeof(Service1), wcfUri);

                //支持NetTcpBinding
                NetTcpBinding netTcpBind = new NetTcpBinding();
                netTcpBind.Security.Mode = SecurityMode.None;
                netTcpBind.MaxBufferPoolSize = Int32.MaxValue;
                netTcpBind.MaxBufferSize = Int32.MaxValue;
                netTcpBind.MaxConnections = Int16.MaxValue;
                netTcpBind.MaxReceivedMessageSize = Int32.MaxValue;

                //支持WSHttpBinding
                WSHttpBinding wsHttpBind = new WSHttpBinding();
                wsHttpBind.Security.Mode = SecurityMode.None;
                wsHttpBind.MaxReceivedMessageSize = Int32.MaxValue;
                wsHttpBind.MaxBufferPoolSize = Int32.MaxValue;
                wsHttpBind.AllowCookies = true;

                //元数据地址
                ServiceMetadataBehavior metadata = new ServiceMetadataBehavior();
                metadata.HttpGetEnabled = true;
                metadata.HttpGetUrl = new Uri("http://10.68.198.41:8001/mex");
                serviceHost.AddServiceEndpoint(typeof(IService1), wsHttpBind, "WCFServer");
                serviceHost.Description.Behaviors.Add(metadata);

                serviceHost.Open();

 

二、客户端连接代码:首先要引用这个服务,同时要注意一下引用后的命名空间。如“using NewsRemindWinApp.ServiceReference1;”

            //方式1:不用配置XML
            //EndpointAddress address = new EndpointAddress("http://10.66.237.118:8001/WCF/WCFServer");
            //WSHttpBinding wsHttpBind = new WSHttpBinding();
            //wsHttpBind.Security.Mode = SecurityMode.None;
            //wsHttpBind.MaxReceivedMessageSize = Int32.MaxValue;
            //wsHttpBind.MaxBufferPoolSize = Int32.MaxValue;
            //wsHttpBind.AllowCookies = true;
            //ChannelFactory<IService1> factory = new ChannelFactory<IService1>(wsHttpBind, address);
            //IService1 channel = factory.CreateChannel();
            //MSGContract msg = new MSGContract();
            //msg.MsgReceiver = "test";
            //msg.MsgTitle = "WCF消息测试";
            //msg.MESSAGES = "能看到就表示OK了";
            //channel.SendMSG(msg);

 

            //方式2:从config文件中直接利用
            Service1Client client = new Service1Client();
            MSGContract msg1 = new MSGContract();
            msg1.MsgReceiver = "test";
            msg1.MsgTitle = "WCF消息测试";
            msg1.MESSAGES = "能看到就表示OK了";
            client.SendMSG(msg1);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值