作者热门文章
- ubuntu12.04环境下使用kvm ioctl接口实现最简单的虚拟机
- Ubuntu 通过无线网络安装Ubuntu Server启动系统后连接无线网络的方法
- 在Ubuntu上搭建网桥的方法
- ubuntu 虚拟机上网方式及相关配置详解
CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.
这篇CFSDN的博客文章分享WCF聊天程序--WCFChat实现代码由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.
无意中在一个国外的站点下到了一个利用wcf实现聊天的程序,作者是:nikola paljetak。研究了一下,自己做了测试和部分修改,感觉还不错,分享给大家。 先来看下运行效果: 开启服务: 客户端程序: 程序分为客户端和服务器端:
------------服务器端:
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"
);
}
|
否则在生成代理类的时候会报错如下的错误:
源码下载: /files/gaoweipeng/wcfchat.rar 。
最后此篇关于分享WCF聊天程序--WCFChat实现代码的文章就讲到这里了,如果你想了解更多关于分享WCF聊天程序--WCFChat实现代码的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。
我是一名优秀的程序员,十分优秀!