本文實例為大家分享了java websocket實現聊天消息推送功能的具體代碼,供大家參考,具體內容如下
環境:
jdk.1.7.0_51
apache-tomcat-7.0.53
java jar包:tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar
chatannotation消息發送類:
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
|
import java.io.ioexception; import java.util.hashmap; import java.util.map; import java.util.concurrent.atomic.atomicinteger; import javax.websocket.onclose; import javax.websocket.onerror; import javax.websocket.onmessage; import javax.websocket.onopen; import javax.websocket.session; import javax.websocket.server.serverendpoint; import org.apache.juli.logging.log; import org.apache.juli.logging.logfactory; import com.util.htmlfilter; /** * websocket 消息推送服務類 * @author 胡漢三 * * 2014-11-18 下午7:53:13 */ @serverendpoint (value = "/websocket/chat" ) public class chatannotation { private static final log log = logfactory.getlog(chatannotation. class ); private static final string guest_prefix = "guest" ; private static final atomicinteger connectionids = new atomicinteger( 0 ); private static final map<string,object> connections = new hashmap<string,object>(); private final string nickname; private session session; public chatannotation() { nickname = guest_prefix + connectionids.getandincrement(); } @onopen public void start(session session) { this .session = session; connections.put(nickname, this ); string message = string.format( "* %s %s" , nickname, "has joined." ); broadcast(message); } @onclose public void end() { connections.remove( this ); string message = string.format( "* %s %s" , nickname, "has disconnected." ); broadcast(message); } /** * 消息發送觸發方法 * @param message */ @onmessage public void incoming(string message) { // never trust the client string filteredmessage = string.format( "%s: %s" , nickname, htmlfilter.filter(message.tostring())); broadcast(filteredmessage); } @onerror public void onerror(throwable t) throws throwable { log.error( "chat error: " + t.tostring(), t); } /** * 消息發送方法 * @param msg */ private static void broadcast(string msg) { if (msg.indexof( "guest0" )!=- 1 ){ senduser(msg); } else { sendall(msg); } } /** * 向所有用戶發送 * @param msg */ public static void sendall(string msg){ for (string key : connections.keyset()) { chatannotation client = null ; try { client = (chatannotation) connections.get(key); synchronized (client) { client.session.getbasicremote().sendtext(msg); } } catch (ioexception e) { log.debug( "chat error: failed to send message to client" , e); connections.remove(client); try { client.session.close(); } catch (ioexception e1) { // ignore } string message = string.format( "* %s %s" , client.nickname, "has been disconnected." ); broadcast(message); } } } /** * 向指定用戶發送消息 * @param msg */ public static void senduser(string msg){ chatannotation c = (chatannotation)connections.get( "guest0" ); try { c.session.getbasicremote().sendtext(msg); } catch (ioexception e) { log.debug( "chat error: failed to send message to client" , e); connections.remove(c); try { c.session.close(); } catch (ioexception e1) { // ignore } string message = string.format( "* %s %s" , c.nickname, "has been disconnected." ); broadcast(message); } } } |
htmlfilter工具類:
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
|
/** * html 工具類 * * @author 胡漢三 */ public final class htmlfilter { public static string filter(string message) { if (message == null ) return ( null ); char content[] = new char [message.length()]; message.getchars( 0 , message.length(), content, 0 ); stringbuilder result = new stringbuilder(content.length + 50 ); for ( int i = 0 ; i < content.length; i++) { switch (content[i]) { case '<' : result.append( "<" ); break ; case '>' : result.append( ">" ); break ; case '&' : result.append( "&" ); break ; case '"' : result.append( "" "); break ; default : result.append(content[i]); } } return (result.tostring()); } } |
頁面:
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
|
<%@ page language= "java" import = "java.util.*" pageencoding= "utf-8" %> <% string path = request.getcontextpath(); string basepath = request.getscheme()+ "://" +request.getservername()+ ":" +request.getserverport()+path+ "/" ; %> <?xml version= "1.0" encoding= "utf-8" ?> <html xmlns= "http://www.w3.org/1999/xhtml" xml:lang= "en" > <head> <title>測試</title> <style type= "text/css" > input#chat { width: 410px } #console-container { width: 400px; } #console { border: 1px solid #cccccc; border-right-color: # 999999 ; border-bottom-color: # 999999 ; height: 170px; overflow-y: scroll; padding: 5px; width: 100 %; } #console p { padding: 0 ; margin: 0 ; } </style> <script type= "text/javascript" > var chat = {}; chat.socket = null ; chat.connect = (function(host) { if ( 'websocket' in window) { chat.socket = new websocket(host); } else if ( 'mozwebsocket' in window) { chat.socket = new mozwebsocket(host); } else { console.log( 'error: websocket is not supported by this browser.' ); return ; } chat.socket.onopen = function () { console.log( 'info: websocket connection opened.' ); document.getelementbyid( 'chat' ).onkeydown = function(event) { if (event.keycode == 13 ) { chat.sendmessage(); } }; }; chat.socket.onclose = function () { document.getelementbyid( 'chat' ).onkeydown = null ; console.log( 'info: websocket closed.' ); }; chat.socket.onmessage = function (message) { console.log(message.data); }; }); chat.initialize = function() { if (window.location.protocol == 'http:' ) { chat.connect( 'ws://' + window.location.host + '/socket2/websocket/chat' ); } else { chat.connect( 'wss://' + window.location.host + '/socket2/websocket/chat' ); } }; chat.sendmessage = (function() { var message = document.getelementbyid( 'chat' ).value; if (message != '' ) { chat.socket.send(message); document.getelementbyid( 'chat' ).value = '' ; } }); var console = {}; console.log = (function(message) { var console = document.getelementbyid( 'console' ); var p = document.createelement( 'p' ); p.style.wordwrap = 'break-word' ; p.innerhtml = message; console.appendchild(p); while (console.childnodes.length > 25 ) { console.removechild(console.firstchild); } console.scrolltop = console.scrollheight; }); chat.initialize(); document.addeventlistener( "domcontentloaded" , function() { // remove elements with "noscript" class - <noscript> is not allowed in xhtml var noscripts = document.getelementsbyclassname( "noscript" ); for (var i = 0 ; i < noscripts.length; i++) { noscripts[i].parentnode.removechild(noscripts[i]); } }, false ); </script> </head> <body> <div class = "noscript" ><h2 style= "color: #ff0000" >seems your browser doesn't support javascript! websockets rely on javascript being enabled. please enable javascript and reload this page!</h2></div> <div> <p> <input type= "text" placeholder= "請輸入內容" id= "chat" /> </p> <div id= "console-container" > <div id= "console" /> </div> </div> </body> </html> |
可指定發送給某個用戶,也可全部發送,詳情見chatannotation類的broadcast方法。
程序發布時記得刪除tomcat-coyote.jar、tomcat-juli.jar、websocket-api.jar這三個jar包在啟動tomcat。
程序截圖,guest0用戶發送信息的信息,在后臺進行了判斷只發送給自己:
guest1:
guest2:
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/hzw2312/article/details/41252159/