如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 # W! b7 k, G# ]1 U
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
. I, u6 o! B s
8 I$ H! N( a- \' K" g
3 ]; L- P$ T2 D该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开, @' t3 q- Q$ w
- }4 v: w; r! G4 b# s9 K2 i* I/ M3 K8 B
- 0 j8 ?6 H+ u7 ]3 b/ n K0 E
- socket.onmessage = function(){
4 ~1 m! t6 O. N% c - //在event.data消息数据8 K$ v5 I& z+ b* v6 e) G; w
- }
0 d# o* ?1 a4 q( k0 v! P, k
+ H, p1 o6 }7 g! d+ k* X- socket.onclose = function(){; Q2 W% }& d2 p/ p
- //关闭WebSocket3 h/ H) O6 y1 g' P3 b6 j3 M
- }6 P+ |; p2 @7 {
& X( u9 \7 U' U, Z- socket.onerror = function(){
" R' C( H/ L' m3 x: B - //错误触发
! g9 r' ~ [! Q! Z) @: ?7 l* A - }
复制代码 , }4 Q. E9 l3 q) E/ F
! Y7 j/ ^3 ?( S5 s% y: H2 Y通过套接口发送数据,调用socket.send: 0 i7 W" G' W9 D; h% K# _' }" |3 g- W
7 c [: Q3 N. @6 K2 b
I$ p- x. H( T代码附上: - <!DOCTYPE html><html>7 e* b9 o" Q* U1 ]
- <head>0 V1 ]7 M& A* U9 V% ~! Q7 N
- <meta charset="UTF-8">5 J$ m+ J; k S2 ]6 B6 e& G
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
/ U7 _6 {3 o9 i3 L: [$ X' F - <title>WebSocket</title>1 z& W' t0 o) H& U* ?$ t
- </head>
8 j7 Z5 \6 u/ X' Z' x" @ - <body>
0 j8 J' x2 d. g' ?' a) a7 `, J - </body>" j$ r( q! G9 _7 C( g9 W9 m3 ~
- <script>
8 r% i, A! K4 `/ x' K9 O/ T - var socket;
3 m! p# L4 S) d$ g - if (window.WebSocket) {" G( s" z6 v/ y5 `# w
- socket = new WebSocket("ws://localhost:8080/myapp");1 p; x- r# b+ P( a9 j
- socket.onmessage = function(event) {
- G/ a5 ]2 k* M$ l9 t9 h - alert("Received data from websocket: " + event.data);+ v$ T0 U. N5 l9 w
- }
2 M: j. x' L- X/ f; W! X9 L - socket.onopen = function(event) {% g2 b% `( R/ u9 ] A
- alert("Web Socket opened!");
0 y% M! d1 p, K6 d9 @2 |. D - };5 p% l1 g, W3 m% b
- socket.onclose = function(event) {5 @/ M& ^* V8 O2 N0 _4 H
- alert("Web Socket closed.");
x! H) U8 E7 P+ }! {2 i$ h4 T - };: m0 Q4 `, ^0 k; b/ \' h/ L
- } else {( ?, a. B" A2 c) y' M
- alert("Your browser does not support Websockets. (Use Chrome)");
) A- w0 p' e. U- |0 f( y - }5 Q; ^& |, z; @0 D6 Q) d
- 1 o: W: t2 `) y& w% q
- function send(message) {
9 |0 Z! I R) H) q. A1 W4 F - if (!window.WebSocket) {- i7 R, T8 J3 H; F6 s4 ^
- return;% c+ g3 M. q' H! k: u( I
- }# F4 h5 Z6 v) {7 z
- if (socket.readyState == WebSocket.OPEN) { k" b1 R4 C7 z
- socket.send(message);7 U& j4 Y% g" y
- } else {1 t! H: B* [, ?6 T: S, K1 d" ?* x
- alert("The socket is not open.");
& z0 \# E B* g5 M. c% @ - }
1 y% ?0 t# e) G1 | - }5 o2 }9 F: n1 k6 }4 D4 |& s
- </script>4 D) D' ]( {# F0 P( c/ Q9 c9 w
- </html>
复制代码 0 ` K' H0 C% y# A, v9 `& N
& h& F& p1 J) J+ o
4 J7 [2 v9 m3 ?+ X8 c |