使用wcf的双工模式做的一个控制台聊天app

//wcf 服务

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“IService1”。
    [ServiceContract(CallbackContract = typeof(iMyclass))]
    public interface IService1
    {
         
        [OperationContract]
        string  Send(string id,string pid, string str);
        [OperationContract]
        string Register(string id);
        [OperationContract]
        List<string> ALLhost();
    
    }
    [ServiceContract]
    public interface iMyclass
    {
        [OperationContract(IsOneWay = true)]//回调函数方法必须加IsOneWay=true
        void Reciver(string str);
    }

    
 
}

  

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WcfService1
{
    // 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Service1”。
    public class Service1 : IService1
    {
        public static Dictionary<string, iMyclass> hostdic;
        public static List<string> allhost;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="id">发送人</param>
        /// <param name="pid">接受人</param>
        /// <param name="str">内容</param>
        /// <returns></returns>
        public string Send(string id,string pid, string str)
        {
            try
            {
               
                foreach (var d in hostdic)
                {
                    if (d.Key == pid)
                    {
                        d.Value.Reciver(id+"发送:"+str);
                    }
                }
             //iMyclass myclass= OperationContext.Current.GetCallbackChannel<iMyclass>();
             //myclass.Reciver("你好");
                return "1";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        public List<string> ALLhost()
        {
            return allhost;
        }
        public string Register(string id)
        {
            if (hostdic == null)
            {
                hostdic = new Dictionary<string, iMyclass>();
            }
            if (allhost == null)
            {
                allhost = new List<string>();
            }
            
                iMyclass imyclass = OperationContext.Current.GetCallbackChannel<iMyclass>();
                hostdic.Add(id, imyclass);

                allhost.Add(id);

            
            return id;
        }
    
    }
}

  //宿主

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace ServerHost
{
    class Program
    {
        static void Main(string[] args)
        {
            ServiceHost serverhost = new ServiceHost(typeof(WcfService1.Service1));
            serverhost.Open();
            Console.WriteLine("open");
            Console.ReadKey();
        }
    }
}

  //宿主配置文件

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
	<system.serviceModel>
		<services>
			<service name="WcfService1.Service1">
				<endpoint address="net.tcp://192.168.1.12:3721/calculatorservice"
//改为本地的ip
binding="netTcpBinding" contract="WcfService1.IService1" bindingConfiguration ="TicketBindingConfiguration"/> </service> </services> <bindings> <netTcpBinding> <binding name="TicketBindingConfiguration" openTimeout="00:10:10" receiveTimeout="00:10:10" sendTimeout="00:10:10" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647"> <security mode="None" /> <readerQuotas maxStringContentLength="6553600" maxArrayLength="6553600" /> </binding> </netTcpBinding> </bindings> </system.serviceModel> </configuration>

  //客户端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WcfService1;
using System.ServiceModel;
using System.Configuration;
namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                myclass myclass = new myclass();
                //  myclass.contentevent += receive;
                InstanceContext callback = new InstanceContext(myclass);
                //  ChannelFactory<IService1> channl = new ChannelFactory<IService1>(  "wcfserver");  如果不是双工模式没有回调的话就使用这个
                DuplexChannelFactory<IService1> channl = new DuplexChannelFactory<IService1>(callback, "wcfserver");
                IService1 IService1 = channl.CreateChannel();
                Console.WriteLine("请输入自己的用户名");
                string id = Console.ReadLine();
                string str = IService1.Register(id.Trim());
                Console.WriteLine(str);
                while (true)
                {
                    Console.WriteLine("输入发送数据");
                    string info = Console.ReadLine();
                    Console.WriteLine("输入接受人");
                    string piduser = Console.ReadLine();
                    Console.WriteLine("发送给" + piduser.Trim() + ":" + info.Trim());
                    IService1.Send(id,piduser.Trim(), info.Trim());
                }
                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
        }
    }
    public class myclass : iMyclass
    {
        // public delegate void conten(string str);
        //  public event conten contentevent;
        public void Reciver(string str)
        {
            Console.WriteLine("{0}:" + str, System.DateTime.Now);
            // contentevent(str);
        }

    }
}

  //客户端配置文件

<?xml version="1.0" encoding="utf-8" ?>


<configuration>
	<system.serviceModel>
		<client>

			<endpoint name="wcfserver" address="net.tcp://192.168.1.12:3721/calculatorservice" //改为本地的ip
					  binding="netTcpBinding"
					  contract="WcfService1.IService1"
						bindingConfiguration ="TicketBindingConfiguration"/>

		</client>
		<bindings>
			<netTcpBinding>
				<binding  name="TicketBindingConfiguration"  openTimeout="00:10:10" receiveTimeout="00:10:10"    sendTimeout="00:10:10"  maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
					<security mode="None" />
					<readerQuotas  maxStringContentLength="6553600" maxArrayLength="6553600" />
				</binding>
			</netTcpBinding>
		</bindings>
	</system.serviceModel>
</configuration>

  

转载于:https://www.cnblogs.com/wlzhang/p/3791142.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值