如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码
( D* }* \) {' o% O/ Z与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 6 p- { S& [) `# q
6 C. x( z* B* B7 R: H; r9 p; D5 K# |" \- N) t1 g0 v
该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开
; H1 |) |1 K5 Q5 `* d - }
' Y8 l! ?& L- T/ u
" j' F( T8 T; ^" r+ q- socket.onmessage = function(){$ Q3 h5 ~: p* s
- //在event.data消息数据( j6 |- ~) }9 P' ^
- }3 A" G" u! D/ X+ q% Y
4 h7 j& v7 c( ^+ y9 _- socket.onclose = function(){0 a! h' n' @) n1 w6 ?
- //关闭WebSocket
9 s ~! S7 C/ J% j% O - }. B/ `5 m7 b" N8 E8 F; a6 w* m
- & I) N4 a( m8 F2 v" D p- W5 z, A
- socket.onerror = function(){# ?* X% E, P5 e/ J0 ~; S9 M
- //错误触发
0 Q) P8 ~' R6 a* h3 G# }! E# \ - }
复制代码
: t; ]: M5 A. U1 ]" v" ~
% h" E2 {4 b6 `通过套接口发送数据,调用socket.send: , G2 \0 U5 v* F) g }
3 V) I0 p/ K+ k/ b
. Z4 f4 T1 q0 n: a9 \8 ^5 o( E- r5 _代码附上: - <!DOCTYPE html><html>' m1 b4 x3 ~0 x' c
- <head>6 h! [7 ]8 K: p9 e l
- <meta charset="UTF-8">7 ?7 m5 O) s$ r+ `" h2 _
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">9 ~; D( E! p9 v3 T* v: H& W' q
- <title>WebSocket</title>
0 A( E' j9 u" a" q+ e - </head>
# i2 B. @* y6 K) k# ? - <body>
; f# h& u2 J. Y9 ^ - </body>
. X8 v( _" k5 {- ^( m; L7 ] - <script>
7 E0 P1 @" X4 x. o9 ]& j+ a/ H - var socket;
4 J# s& x' Y$ X9 F+ b; N - if (window.WebSocket) {+ [4 C2 B& ?9 o+ o' V
- socket = new WebSocket("ws://localhost:8080/myapp");
6 e0 x/ G% {# [) m3 G* r( q8 p6 U - socket.onmessage = function(event) {
% D1 M$ X/ h6 N2 I - alert("Received data from websocket: " + event.data);+ P. o2 g$ h; D( S! \! i, m
- }
4 {8 M( Q6 |9 I( w - socket.onopen = function(event) {
0 z; L5 U" Q! P2 _ - alert("Web Socket opened!");
5 D. J* ~3 m# F - };3 ?- ?; I2 O- N- R4 T! _; B5 d
- socket.onclose = function(event) {1 L1 ?( ? E$ J3 T
- alert("Web Socket closed.");& o& d* |/ C5 j0 u" G
- };! Q; _$ Y3 \& H/ J
- } else {
% E2 p0 B2 P; D! Y5 X* C- r' { - alert("Your browser does not support Websockets. (Use Chrome)");$ s( R7 `% e$ ?5 w
- }
+ P; N6 N+ z( Y% t8 [( g
6 b4 z6 n' T/ l1 L5 ]6 b- function send(message) {( q' R; m! ^% J4 \. M# J7 o3 r
- if (!window.WebSocket) {
7 a8 W& N5 d8 C. ` - return;) S3 i! F) x1 X9 ?5 |
- }+ |- ?$ D: L8 x+ Y* \! g4 S# H
- if (socket.readyState == WebSocket.OPEN) {
/ N! K2 q' v* U$ @2 N4 g' p - socket.send(message);
# e1 {* _3 P$ R - } else {
9 j1 ^, O* k: Z/ W6 u7 c* T, o. d - alert("The socket is not open.");
$ B( }- w! j- `- b, A, k - }
; D: p' B- n. ~) K# h/ |- C - }) f8 |% D) f' a* t6 I
- </script>- }' G( f4 _; r* G2 A; {5 ]
- </html>
复制代码 / }5 Y7 O" D* u) a
" T4 W5 ~; Q6 q# q J+ M& b; b7 O6 }2 P) p6 R0 V
|