很早以前为了快速达到效果,使用轮询实现了在线聊天功能,后来无意接触了socket,关于socket我的理解是进程间通信,首先要有服务器跟客户端,服务的启动监听某ip端口定位该进程,客户端开启socket分配ip端口连接服务端ip端口,于是两个进程间便可以通信了。下面简单画个图理解。
but,今天还是准备分享websocket的使用,先上效果,再贴代码。
第一步启动socket服务。
然后连接客户端连接服务器,加入聊天室,分别使用googel(白玉京,沈浪),火狐(楚留香),ie(李寻欢)进行测试,效果如下。
*
*****************断开一下。
******************断开一下。
下面是本次测试源码。
服务端:
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
|
public class testwebsocketcontroller : controller { websocketserver server; list<sessioninfo> listsession = new list<sessioninfo>(); public actionresult index() { return view(); } //服务启动 public string start() { var ip = "192.168.1.106" ; var port = "1010" ; server = new websocketserver(); if (!server.setup(ip, int .parse(port))) { return "websocket服务启动error" ; } //新的会话连接 server.newsessionconnected += sessionconnected; //会话关闭 server.sessionclosed += sessionclosed; //新的消息接收 server.newmessagereceived += messagereceived; if (!server.start()) { //处理监听失败消息 return "error" ; } return "success" ; } /// <summary> /// 会话关闭 /// </summary> /// <param name="session"></param> /// <param name="value"></param> private void sessionclosed(websocketsession session, supersocket.socketbase.closereason value) { debug.writeline( "会话关闭,关闭原因:{0} 来自:{1} 时间:{2:hh:mm:ss}" , value, session.remoteendpoint, datetime.now); //sendmsgtoremotepoint(sessionid, sessionid + "已断开"); var sessionremove = listsession.firstordefault(s => s.sessionid == session.sessionid); listsession.remove(sessionremove); } /// <summary> /// 会话连接 /// </summary> /// <param name="session"></param> private void sessionconnected(websocketsession session) { debug.writeline( "新的会话连接 来自:{0} sessionid:{1} 时间:{2:hh:mm:ss}" , session.remoteendpoint, session.sessionid, datetime.now); listsession.add( new sessioninfo { sessionid = session.sessionid, endpoint = session.remoteendpoint.tostring() }); } /// <summary> /// 消息接收 /// </summary> /// <param name="session"></param> /// <param name="value"></param> private void messagereceived(websocketsession session, string value) { //反序列化消息内容 var message = jsonconvert.deserializeobject<messageinfo>(value); foreach (var item in listsession) { ///发送消息 sendmsg(item.sessionid, string.format( "{0}发来消息:{1}" , message.name, message.message)); } } // <summary> /// 发送消息 /// </summary> /// <param name="sessionid"></param> /// <param name="msg"></param> private void sendmsg(string sessionid, string msg) { var appsession = server.getappsessionbyid(sessionid); if (appsession != null ) appsession.send(msg); } public class messageinfo { public string name { get; set; } public string message { get; set; } } public class sessioninfo { public string sessionid { get; set; } public string endpoint { get; set; } //public string name { get; set; } } } |
客户端:
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
|
@{ viewbag.title = "index" ; } <h2>index</h2> <script src= "../scripts/jquery-1.8.2.js" ></script> <input type= "text" id= "txtname" /> <input type= "button" value= "加入聊天室" id= "btnconnection" /> <input type= "button" value= "离开聊天室" id= "btndisconnection" /> <input type= "text" id= "txtinput" /> <input type= "button" value= "发送" id= "btnsend" /> <div id= "msg" ></div> <script language= "javascript" type= "text/javascript" > var ws; var url = "ws://192.168.1.106:1010" $( "#btnconnection" ).click(function () { if ( "websocket" in window) { ws = new websocket(url); } else if ( "mozwebsocket" in window) { ws = new mozwebsocket(url); } else alert( "浏览器版本过低,请升级您的浏览器" ); //注册各类回调 ws.onopen = function () { $( "#msg" ).append($( "#txtname" ).val() + "加入聊天室<br />" ); } ws.onclose = function () { $( "#msg" ).append($( "#txtname" ).val() + "离开聊天室<br />" ); } ws.onerror = function () { $( "#msg" ).append( "数据传输发生错误<br />" ); } ws.onmessage = function (receivemsg) { $( "#msg" ).append(receivemsg.data + "<br />" ); } //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。 window.onbeforeunload = function () { ws.close(); } }); //$("#btndisconnection").click(function () { // $("#msg").append($("#txtname").val() + "离开聊天室<br />"); // ws.close(); //}); $( "#btnsend" ).click(function () { if (ws.readystate == websocket.open) { var message = "{\"name\":\"" + $( "#txtname" ).val() + "\",\"message\":\"" + $( "#txtinput" ).val() + "\"}" ; ws.send(message); } else { $( "#msg" ).text( "connection is closed!" ); } }); </script> |
总结
以上所述是小编给大家介绍的java中使用websocket实现在线聊天功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对服务器之家网站的支持!
原文链接:http://www.cnblogs.com/baiyujing/p/8458567.html