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

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#将Tensorflow训练的.pb文件用在生产环境详解

    如何使用C#将Tensorflow训练的.pb文件用在生产环境详解

    这篇文章主要给大家介绍了关于如何使用C#将Tensorflow训练的.pb文件用在生产环境的相关资料,文中通过示例代码介绍的非常详细,需要的朋友可以参考借鉴...

    bbird201811792022-03-05
  • C#深入理解C#的数组

    深入理解C#的数组

    本篇文章主要介绍了C#的数组,数组是一种数据结构,详细的介绍了数组的声明和访问等,有兴趣的可以了解一下。...

    佳园9492021-12-10
  • C#利用C#实现网络爬虫

    利用C#实现网络爬虫

    这篇文章主要介绍了利用C#实现网络爬虫,完整的介绍了C#实现网络爬虫详细过程,感兴趣的小伙伴们可以参考一下...

    C#教程网11852021-11-16
  • C#三十分钟快速掌握C# 6.0知识点

    三十分钟快速掌握C# 6.0知识点

    这篇文章主要介绍了C# 6.0的相关知识点,文中介绍的非常详细,通过这篇文字可以让大家在三十分钟内快速的掌握C# 6.0,需要的朋友可以参考借鉴,下面来...

    雨夜潇湘8272021-12-28
  • C#SQLite在C#中的安装与操作技巧

    SQLite在C#中的安装与操作技巧

    SQLite,是一款轻型的数据库,用于本地的数据储存。其优点有很多,下面通过本文给大家介绍SQLite在C#中的安装与操作技巧,感兴趣的的朋友参考下吧...

    蓝曈魅11162022-01-20
  • C#C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    C#设计模式之Strategy策略模式解决007大破密码危机问题示例

    这篇文章主要介绍了C#设计模式之Strategy策略模式解决007大破密码危机问题,简单描述了策略模式的定义并结合加密解密算法实例分析了C#策略模式的具体使用...

    GhostRider10972022-01-21
  • C#VS2012 程序打包部署图文详解

    VS2012 程序打包部署图文详解

    VS2012虽然没有集成打包工具,但它为我们提供了下载的端口,需要我们手动安装一个插件InstallShield。网上有很多第三方的打包工具,但为什么偏要使用微软...

    张信秀7712021-12-15
  • C#C#微信公众号与订阅号接口开发示例代码

    C#微信公众号与订阅号接口开发示例代码

    这篇文章主要介绍了C#微信公众号与订阅号接口开发示例代码,结合实例形式简单分析了C#针对微信接口的调用与处理技巧,需要的朋友可以参考下...

    smartsmile20127762021-11-25