博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
重温WCF之群聊天程序(十)
阅读量:6005 次
发布时间:2019-06-20

本文共 5669 字,大约阅读时间需要 18 分钟。

完成的效果图:

服务器端代码:

using System;using System.Collections.Generic;using System.Linq;using System.ServiceModel;using System.ServiceModel.Description;using System.Text;using System.Threading.Tasks;namespace SendMessageHostConsoleApplication{    [ServiceContract(SessionMode=SessionMode.Required,CallbackContract=typeof(ICallback))]    public interface IService    {        ///         /// 启动会话        ///         [OperationContract(IsOneWay=true,IsInitiating=true,IsTerminating=false)]        void Begin();        ///         /// 客户端调用服务器端发送消息        ///         ///         ///         ///         [OperationContract(IsOneWay = true)]        void SendMessage(string nick,string msg,DateTime sendTime);        ///         /// 终止会话        ///         [OperationContract(IsOneWay=true,IsInitiating=false,IsTerminating=true)]        void End();    }    public interface ICallback    {        ///         /// 服务器端调用客户端发送消息        ///         ///         ///         ///         [OperationContract(IsOneWay=true)]        void SendToClients(string nick,string msg,DateTime sendTime);    }    [ServiceBehavior(IncludeExceptionDetailInFaults=true,InstanceContextMode=InstanceContextMode.PerSession)]    public class MyService : IService    {        public static Dictionary
ClientCallBacks = new Dictionary
(); public void Begin() { string sessionId = OperationContext.Current.SessionId; ICallback cb = OperationContext.Current.GetCallbackChannel
(); MyService.ClientCallBacks[sessionId] = cb; } public void SendMessage(string nick, string msg, DateTime sendTime) { foreach (ICallback c in MyService.ClientCallBacks.Values) { if (c != null) { c.SendToClients(nick, msg, sendTime); } } } public void End() { string sessionId = OperationContext.Current.SessionId; if (MyService.ClientCallBacks.ContainsKey(sessionId)) { MyService.ClientCallBacks.Remove(sessionId); } } } public class Program { public static void Main(string[] args) { using (ServiceHost host = new ServiceHost(typeof(MyService))) { NetTcpBinding bingding = new NetTcpBinding(); bingding.Security.Mode = SecurityMode.None;//不需要安全模式 host.AddServiceEndpoint(typeof(IService), bingding, "net.tcp://127.0.0.1:8868/channel"); ServiceMetadataBehavior behavior = new ServiceMetadataBehavior(); behavior.HttpGetEnabled = true; behavior.HttpGetUrl = new Uri("http://127.0.0.1:8888/WSDL"); //httpGetUrl客户端引用的地址 host.Description.Behaviors.Add(behavior); host.Opened += delegate { Console.WriteLine("服务已启动"); Console.ReadKey(); }; host.Open(); } } }}

客户端调用代码:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.ServiceModel;using System.Text;using System.Threading.Tasks;using System.Windows.Forms;namespace SendMessageClientWindowsFormsApplication{        public partial class Form1 : Form    {        private WS.ServiceClient client = null;        public Form1()        {            InitializeComponent();            MyCallback callback = new MyCallback();            callback.MessageReceived += callback_MessageReceived;            var instanceContext = new InstanceContext(callback);            client = new WS.ServiceClient(instanceContext);            client.Begin();            this.FormClosed += Form1_FormClosed;        }        void Form1_FormClosed(object sender, FormClosedEventArgs e)        {            client.End();        }        private void btnSend_Click(object sender, EventArgs e)        {                 client.SendMessage(this.txtNick.Text, this.txtSendMsg.Text, DateTime.Now);        }        void callback_MessageReceived(object sender, CallbackRecEventArgs e)        {            ListViewItem item = new ListViewItem();            Font font = new System.Drawing.Font(new FontFamily("宋体"), 12,FontStyle.Bold);            item.Font = font;            item.ForeColor = Color.Blue;            if (e.Nick == this.txtNick.Text)            {                item.ForeColor = Color.Green;            }            item.Text = e.Nick + "        " + e.SendTime+"\r\n";            listView1.Items.Add(item);            listView1.Items.Add(e.Message);            this.txtSendMsg.Text = "";        }    }    public class MyCallback : WS.IServiceCallback    {        public void SendToClients(string nick, string msg, DateTime sendTime)        {            if (this.MessageReceived != null)            {                CallbackRecEventArgs arg = new CallbackRecEventArgs(nick, msg, sendTime);                this.MessageReceived(this, arg);            }        }        public event EventHandler
MessageReceived; } public class CallbackRecEventArgs : EventArgs { private string _Nick, _Msg; private DateTime _time; public CallbackRecEventArgs(string nk, string m, DateTime t) { _Nick = nk; _Msg = m; _time = t; } public string Nick { get { return _Nick; } } public string Message { get { return _Msg; } } public DateTime SendTime { get { return _time; } } }}

 

转载地址:http://vzpmx.baihongyu.com/

你可能感兴趣的文章
linux文件存取 inode解读
查看>>
android edittext不弹出软键盘
查看>>
windows下安装和配置nginx
查看>>
selinux
查看>>
第3章 远程连接管理Linux实践
查看>>
透析Linux系统编程
查看>>
数据库Sqlite文件的增删改查
查看>>
hdu 1024 Max Sum Plus Plus 小白都可以看得懂的解析
查看>>
shell中常见参数及判断命令
查看>>
VMware Horizon View 7.5 虚拟桌面实施咨询与购买--软件硬件解决方案
查看>>
2018新版驾照驾照psd模板下载
查看>>
【矢量图控件教程】矢量图控件VectorDraw 常见问题整理大全(一)
查看>>
文件系统、服务、防火墙、SELINUX——安全四大金刚
查看>>
RabbitMQ如何保证队列里的消息99.99%被消费?
查看>>
Lync Server 2010的部署系列_第五章 准备 Active Directory 域服务
查看>>
java基本数据类型及运算符小结
查看>>
第一周博客作业
查看>>
Python strip lstrip rstrip使用方法
查看>>
Linux开发工具_1_gcc入门(上)
查看>>
在这里安家了
查看>>