服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - C# - 分享WCF聊天程序--WCFChat实现代码

分享WCF聊天程序--WCFChat实现代码

2021-11-02 13:39C#教程网 C#

无意中在一个国外的站点下到了一个利用WCF实现聊天的程序,作者是:Nikola Paljetak。研究了一下,自己做了测试和部分修改,感觉还不错,分享给大家

无意中在一个国外的站点下到了一个利用wcf实现聊天的程序,作者是:nikola paljetak。研究了一下,自己做了测试和部分修改,感觉还不错,分享给大家。
先来看下运行效果:
开启服务:
分享WCF聊天程序--WCFChat实现代码
客户端程序:
分享WCF聊天程序--WCFChat实现代码
分享WCF聊天程序--WCFChat实现代码
程序分为客户端和服务器端:

------------服务器端:

ichatservice.cs:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
using system;
using system.collections.generic;
using system.linq;
using system.runtime.serialization;
using system.servicemodel;
using system.text;
using system.collections;
 
namespace wcfchatservice
{
  // sessionmode.required 允许session会话。双工协定时的回调协定类型为ichatcallback接口
  [servicecontract(sessionmode = sessionmode.required, callbackcontract = typeof(ichatcallback))]
  public interface ichatservice
  {
    [operationcontract(isoneway = false, isinitiating = true, isterminating = false)]//----->isoneway = false等待服务器完成对方法处理;isinitiating = true启动session会话,isterminating = false 设置服务器发送回复后不关闭会话
    string[] join(string name);//用户加入
 
    [operationcontract(isoneway = true, isinitiating = false, isterminating = false)]
    void say(string msg);//群聊信息
 
    [operationcontract(isoneway = true, isinitiating = false, isterminating = false)]
    void whisper(string to, string msg);//私聊信息
 
    [operationcontract(isoneway = true, isinitiating = false, isterminating = true)]
    void leave();//用户加入
  }
  /// <summary>
  /// 双向通信的回调接口
  /// </summary>
  interface ichatcallback
  {
    [operationcontract(isoneway = true)]
    void receive(string sendername, string message);
 
    [operationcontract(isoneway = true)]
    void receivewhisper(string sendername, string message);
 
    [operationcontract(isoneway = true)]
    void userenter(string name);
 
    [operationcontract(isoneway = true)]
    void userleave(string name);
  }
 
  /// <summary>
  /// 设定消息的类型
  /// </summary>
  public enum messagetype { receive, userenter, userleave, receivewhisper };
  /// <summary>
  /// 定义一个本例的事件消息类. 创建包含有关事件的其他有用的信息的变量,只要派生自eventargs即可。
  /// </summary>
  public class chateventargs : eventargs
  {
    public messagetype msgtype;
    public string name;
    public string message;
  }
}

chatservice.cs

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
using system;
using system.collections.generic;
using system.linq;
using system.runtime.serialization;
using system.servicemodel;
using system.text;
 
namespace wcfchatservice
{
  // instancecontextmode.persession 服务器为每个客户会话创建一个新的上下文对象。concurrencymode.multiple 异步的多线程实例
  [servicebehavior(instancecontextmode = instancecontextmode.persession, concurrencymode = concurrencymode.multiple)]
  public class chatservice : ichatservice
  {
    private static object syncobj = new object();////定义一个静态对象用于线程部份代码块的锁定,用于lock操作
    ichatcallback callback = null;
 
    public delegate void chateventhandler(object sender, chateventargs e);//定义用于把处理程序赋予给事件的委托。
    public static event chateventhandler chatevent;//定义事件
    static dictionary<string, chateventhandler> chatters = new dictionary<string, chateventhandler>();//创建一个静态dictionary(表示键和值)集合(字典),用于记录在线成员,dictionary<(of <(tkey, tvalue>)>) 泛型类
 
    private string name;
    private chateventhandler myeventhandler = null;
 
 
    public string[] join(string name)
    {
      bool useradded = false;
      myeventhandler = new chateventhandler(myeventhandler);//将myeventhandler方法作为参数传递给委托
 
      lock (syncobj)//线程的同步性,同步访问多个线程的任何变量,利用lock(独占锁),确保数据访问的唯一性。
      {
        if (!chatters.containskey(name) && name != "" && name != null)
        {
          this.name = name;
          chatters.add(name, myeventhandler);
          useradded = true;
        }
      }
 
      if (useradded)
      {
        callback = operationcontext.current.getcallbackchannel<ichatcallback>();//获取当前操作客户端实例的通道给ichatcallback接口的实例callback,此通道是一个定义为ichatcallback类型的泛类型,通道的类型是事先服务契约协定好的双工机制。
        chateventargs e = new chateventargs();//实例化事件消息类chateventargs
        e.msgtype = messagetype.userenter;
        e.name = name;
        broadcastmessage(e);
        chatevent += myeventhandler;
        string[] list = new string[chatters.count]; //以下代码返回当前进入聊天室成员的称列表
        lock (syncobj)
        {
          chatters.keys.copyto(list, 0);//将字典中记录的用户信息复制到数组中返回。
        }
        return list;
      }
      else
      {
        return null;
      }
    }
 
    public void say(string msg)
    {
      chateventargs e = new chateventargs();
      e.msgtype = messagetype.receive;
      e.name = this.name;
      e.message = msg;
      broadcastmessage(e);
    }
 
    public void whisper(string to, string msg)
    {
      chateventargs e = new chateventargs();
      e.msgtype = messagetype.receivewhisper;
      e.name = this.name;
      e.message = msg;
      try
      {
        chateventhandler chatterto;//创建一个临时委托实例
        lock (syncobj)
        {
          chatterto = chatters[to]; //查找成员字典中,找到要接收者的委托调用
        }
        chatterto.begininvoke(this, e, new asynccallback(endasync), null);//异步方式调用接收者的委托调用
      }
      catch (keynotfoundexception)
      {
      }
    }
 
    public void leave()
    {
      if (this.name == null)
        return;
 
      lock (syncobj)
      {
        chatters.remove(this.name);
      }
      chatevent -= myeventhandler;
      chateventargs e = new chateventargs();
      e.msgtype = messagetype.userleave;
      e.name = this.name;
      this.name = null;
      broadcastmessage(e);
    }
 
    //回调,根据客户端动作通知对应客户端执行对应的操作
    private void myeventhandler(object sender, chateventargs e)
    {
      try
      {
        switch (e.msgtype)
        {
          case messagetype.receive:
            callback.receive(e.name, e.message);
            break;
          case messagetype.receivewhisper:
            callback.receivewhisper(e.name, e.message);
            break;
          case messagetype.userenter:
            callback.userenter(e.name);
            break;
          case messagetype.userleave:
            callback.userleave(e.name);
            break;
        }
      }
      catch
      {
        leave();
      }
    }
 
    private void broadcastmessage(chateventargs e)
    {
 
      chateventhandler temp = chatevent;
 
      if (temp != null)
      {
        //循环将在线的用户广播信息
        foreach (chateventhandler handler in temp.getinvocationlist())
        {
          //异步方式调用多路广播委托的调用列表中的chateventhandler
          handler.begininvoke(this, e, new asynccallback(endasync), null);
        }
      }
    }
    //广播中线程调用完成的回调方法功能:清除异常多路广播委托的调用列表中异常对象(空对象)
    private void endasync(iasyncresult ar)
    {
      chateventhandler d = null;
 
      try
      {
        //封装异步委托上的异步操作结果
        system.runtime.remoting.messaging.asyncresult asres = (system.runtime.remoting.messaging.asyncresult)ar;
        d = ((chateventhandler)asres.asyncdelegate);
        d.endinvoke(ar);
      }
      catch
      {
        chatevent -= d;
      }
    }
  }
}

------------客户端:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.runtime.interopservices;
using system.servicemodel;
 
namespace wcfchatclient
{
  public partial class chatform : form, ichatservicecallback
  {
    /// <summary>
    /// 该函数将指定的消息发送到一个或多个窗口。此函数为指定的窗口调用窗口程序,直到窗口程序处理完消息再返回。 
    /// </summary>
    /// <param name="hwnd">其窗口程序将接收消息的窗口的句柄</param>
    /// <param name="msg">指定被发送的消息</param>
    /// <param name="wparam">指定附加的消息指定信息</param>
    /// <param name="lparam">指定附加的消息指定信息</param>
    [dllimport("user32.dll")]
    private static extern int sendmessage(intptr hwnd, int msg, int wparam, intptr lparam);
    //当一个窗口标准垂直滚动条产生一个滚动事件时发送此消息给那个窗口,也发送给拥有它的控件
    private const int wm_vscroll = 0x115;
    private const int sb_bottom = 7;
    private int lastselectedindex = -1;
 
    private chatserviceclient proxy;
    private string username;
 
    private waitform wfdlg = new waitform();
    private delegate void handledelegate(string[] list);
    private delegate void handleerrordelegate();
 
    public chatform()
    {
      initializecomponent();
      showinterchatmenuitem(true);
    }
 
    /// <summary>
    /// 连接服务器
    /// </summary>
    private void interchatmenuitem_click(object sender, eventargs e)
    {
      lbonlineusers.items.clear();
      loginform logindlg = new loginform();
      if (logindlg.showdialog() == dialogresult.ok)
      {
        username = logindlg.txtusername.text;
        logindlg.close();
      }
 
      txtchatcontent.focus();
      application.doevents();
      instancecontext site = new instancecontext(this);//为实现服务实例的对象进行初始化
      proxy = new chatserviceclient(site);
      iasyncresult iar = proxy.beginjoin(username, new asynccallback(onendjoin), null);
      wfdlg.showdialog();
    }
 
    private void onendjoin(iasyncresult iar)
    {
      try
      {
        string[] list = proxy.endjoin(iar);
        handleendjoin(list);
 
      }
      catch (exception e)
      {
        handleendjoinerror();
      }
 
    }
    /// <summary>
    /// 错误提示
    /// </summary>
    private void handleendjoinerror()
    {
      if (wfdlg.invokerequired)
        wfdlg.invoke(new handleerrordelegate(handleendjoinerror));
      else
      {
        wfdlg.showerror("无法连接聊天室!");
        exitchatsession();
      }
    }
    /// <summary>
    /// 登录结束后的处理
    /// </summary>
    /// <param name="list"></param>
    private void handleendjoin(string[] list)
    {
      if (wfdlg.invokerequired)
        wfdlg.invoke(new handledelegate(handleendjoin), new object[] { list });
      else
      {
        wfdlg.visible = false;
        showinterchatmenuitem(false);
        foreach (string name in list)
        {
          lbonlineusers.items.add(name);
        }
        appendtext(" 用户: " + username + "--------登录---------" + datetime.now.tostring()+ environment.newline);
      }
    }
    /// <summary>
    /// 退出聊天室
    /// </summary>
    private void outinterchatmenuitem_click(object sender, eventargs e)
    {
      exitchatsession();
      application.exit();
    }
    /// <summary>
    /// 群聊
    /// </summary>
    private void btnchat_click(object sender, eventargs e)
    {
      sayandclear("", txtchatcontent.text, false);
      txtchatcontent.focus();
    }
    /// <summary>
    /// 发送消息
    /// </summary>
    private void sayandclear(string to, string msg, bool pvt)
    {
      if (msg != "")
      {
        try
        {
          communicationstate cs = proxy.state;
          //pvt 公聊还是私聊
          if (!pvt)
          {
            proxy.say(msg);
          }
          else
          {
            proxy.whisper(to, msg);
          }
 
          txtchatcontent.text = "";
        }
        catch
        {
          abortproxyandupdateui();
          appendtext("失去连接: " + datetime.now.tostring() + environment.newline);
          exitchatsession();
        }
      }
    }
    private void txtchatcontent_keypress(object sender, keypresseventargs e)
    {
      if (e.keychar == 13)
      {
        e.handled = true;
        btnchat.performclick();
      }
    }
    /// <summary>
    /// 只有选择一个用户时,私聊按钮才可用
    /// </summary>
    private void lbonlineusers_selectedindexchanged(object sender, eventargs e)
    {
      adjustwhisperbutton();
    }
    /// <summary>
    /// 私聊
    /// </summary>   
    private void btnwhisper_click(object sender, eventargs e)
    {
      if (txtchatdetails.text == "")
      {
        return;
      }
      object to = lbonlineusers.selecteditem;
      if (to != null)
      {
        string receivername = (string)to;
        appendtext("私下对" + receivername + "说: " + txtchatcontent.text);//+ environment.newline
        sayandclear(receivername, txtchatcontent.text, true);
        txtchatcontent.focus();
      }
    }
    /// <summary>
    /// 连接聊天室
    /// </summary>
    private void showinterchatmenuitem(bool show)
    {
      interchatmenuitem.enabled = show;
      outinterchatmenuitem.enabled = this.btnchat.enabled = !show;
    }
    private void appendtext(string text)
    {
      txtchatdetails.text += text;
      sendmessage(txtchatdetails.handle, wm_vscroll, sb_bottom, new intptr(0));
    }
    /// <summary>
    /// 退出应用程序时,释放使用资源
    /// </summary>
    private void exitchatsession()
    {
      try
      {
        proxy.leave();
      }
      catch { }
      finally
      {
        abortproxyandupdateui();
      }
    }
    /// <summary>
    /// 释放使用资源
    /// </summary>
    private void abortproxyandupdateui()
    {
      if (proxy != null)
      {
        proxy.abort();
        proxy.close();
        proxy = null;
      }
      showinterchatmenuitem(true);
    }
    /// <summary>
    /// 接收消息
    /// </summary>
    public void receive(string sendername, string message)
    {
      appendtext(sendername + "说: " + message + environment.newline);
    }
    /// <summary>
    /// 接收私聊消息
    /// </summary>
    public void receivewhisper(string sendername, string message)
    {
      appendtext(sendername + " 私下说: " + message + environment.newline);
    }
    /// <summary>
    /// 新用户登录
    /// </summary>
    public void userenter(string name)
    {
      appendtext("用户 " + name + " --------登录---------" + datetime.now.tostring() + environment.newline);
      lbonlineusers.items.add(name);
    }
    /// <summary>
    /// 用户离开
    /// </summary>
    public void userleave(string name)
    {
      appendtext("用户 " + name + " --------离开---------" + datetime.now.tostring() + environment.newline);
      lbonlineusers.items.remove(name);
      adjustwhisperbutton();
    }
    /// <summary>
    /// 控制私聊按钮的可用性,只有选择了用户时按钮才可用
    /// </summary>
    private void adjustwhisperbutton()
    {
      if (lbonlineusers.selectedindex == lastselectedindex)
      {
        lbonlineusers.selectedindex = -1;
        lastselectedindex = -1;
        btnwhisper.enabled = false;
      }
      else
      {
        btnwhisper.enabled = true;
        lastselectedindex = lbonlineusers.selectedindex;
      }
 
      txtchatcontent.focus();
    }
    /// <summary>
    /// 窗体关闭时,释放使用资源
    /// </summary>
    private void chatform_formclosed(object sender, formclosedeventargs e)
    {
      abortproxyandupdateui();
      application.exit();
    }
  }
}

代码中我做了详细的讲解,相信园友们完全可以看懂。代码中的一些使用的方法还是值得大家参考学习的。这里涉及到了wcf的使用方法,需要注意的是:如果想利用工具生成代理类,需要加上下面的代码:

?
1
2
3
4
5
6
7
if (host.description.behaviors.find<system.servicemodel.description.servicemetadatabehavior>() == 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");
      }

否则在生成代理类的时候会报错如下的错误:

分享WCF聊天程序--WCFChat实现代码

源码下载:
/files/gaoweipeng/wcfchat.rar

延伸 · 阅读

精彩推荐
  • C#C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    C#实现的文件操作封装类完整实例【删除,移动,复制,重命名】

    这篇文章主要介绍了C#实现的文件操作封装类,结合完整实例形式分析了C#封装文件的删除,移动,复制,重命名等操作相关实现技巧,需要的朋友可以参考下...

    Rising_Sun3892021-12-28
  • C#C#直线的最小二乘法线性回归运算实例

    C#直线的最小二乘法线性回归运算实例

    这篇文章主要介绍了C#直线的最小二乘法线性回归运算方法,实例分析了给定一组点,用最小二乘法进行线性回归运算的实现技巧,具有一定参考借鉴价值,需要...

    北风其凉8912021-10-18
  • C#浅谈C# winForm 窗体闪烁的问题

    浅谈C# winForm 窗体闪烁的问题

    下面小编就为大家带来一篇浅谈C# winForm 窗体闪烁的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧...

    C#教程网7962021-12-21
  • C#C# 后台处理图片的几种方法

    C# 后台处理图片的几种方法

    本篇文章主要介绍了C# 后台处理图片的几种方法,非常具有实用价值,需要的朋友可以参考下。...

    IT小伙儿10162021-12-08
  • C#C#基础之泛型

    C#基础之泛型

    泛型是 2.0 版 C# 语言和公共语言运行库 (CLR) 中的一个新功能。接下来通过本文给大家介绍c#基础之泛型,感兴趣的朋友一起学习吧...

    方小白7732021-12-03
  • C#聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题 新手速来围观

    聊一聊C#接口问题,新手速来围观,一个通俗易懂的例子帮助大家更好的理解C#接口问题,感兴趣的小伙伴们可以参考一下...

    zenkey7072021-12-03
  • C#Unity3D UGUI实现缩放循环拖动卡牌展示效果

    Unity3D UGUI实现缩放循环拖动卡牌展示效果

    这篇文章主要为大家详细介绍了Unity3D UGUI实现缩放循环拖动展示卡牌效果,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参...

    诗远3662022-03-11
  • C#c#学习之30分钟学会XAML

    c#学习之30分钟学会XAML

    一个界面程序的核心,无疑就是界面和后台代码,而xaml就是微软为构建应用程序界面而创建的一种描述性语言,也就是说,这东西是搞界面的...

    C#教程网8812021-12-10