如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码
. i4 s1 Y9 X- x: l与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 ( _ k. j7 h. P1 b( _, W
& _* ~ L# }+ l
( E5 E/ B( F) s! |; `9 ?" e该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开) }& U+ |% f( _7 g v$ |
- }1 G' T; [' D' d# |6 N
2 u/ W5 e) c( _, c) L- socket.onmessage = function(){: T- p! c8 S) [! p& j0 \: o
- //在event.data消息数据2 n- Z& k- c: Q7 b. I
- }
# ^( n- E1 e1 r3 l7 {
' s4 r0 q, {9 v; k3 a- socket.onclose = function(){
" R! m% c/ Q; v8 t$ P' p# X. W - //关闭WebSocket
8 s+ Y _8 A2 l) w$ }4 g$ p* Z, T& T - }$ c1 d4 y! [. v- U8 Q5 e
" c- d8 h' b7 B3 D2 L4 [- socket.onerror = function(){
5 M% Y; p% J9 X& r1 _/ g0 E* T2 { - //错误触发
: e& s$ j' x9 d8 m8 G - }
复制代码
' M& K8 e+ f" F- w) K5 F1 u% f: N; j2 b1 H, V
通过套接口发送数据,调用socket.send: r: | W% @9 w( c$ [9 Z. `
0 ?. S+ C: v6 s% e
7 M! Q& T4 h1 h4 z/ l
代码附上: - <!DOCTYPE html><html>
( G# t6 A; K# z3 b& V# y# \ - <head>
- O3 G) T) v& t* o; E1 P$ M - <meta charset="UTF-8">) w1 i6 i6 i; F! E: b h
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">( s) J. J9 W3 E3 R# E0 q+ K j* r3 q3 i
- <title>WebSocket</title>' k# X: D' v; Y
- </head>/ g" T$ K1 Y4 t8 _) c8 N
- <body>1 p3 d" r, k# c: D9 L' q2 P
- </body>8 ]! A" E% ~1 F
- <script>; \ a+ z+ {9 g# V( k$ s n
- var socket;8 f' J; A; A/ }, O; ^
- if (window.WebSocket) {
% f2 K; n, J# b7 t - socket = new WebSocket("ws://localhost:8080/myapp");* F6 z$ a+ R: [: h0 k
- socket.onmessage = function(event) {! ^5 V" W" U$ P$ O& p6 H1 y
- alert("Received data from websocket: " + event.data);
% V0 v# U; p! O" C - }
3 c! q/ ^! {( M; q - socket.onopen = function(event) {
5 Y+ W, e7 t5 Z - alert("Web Socket opened!");
( r. R: i4 F6 r" O, P - };
# {: G8 ~, D4 U9 N1 ?2 w6 H- P, ` - socket.onclose = function(event) {. \% C, B' g4 `3 D2 Y6 }7 E7 c7 Y
- alert("Web Socket closed.");" E& H8 V* F# K0 o0 \
- };5 \4 X+ k# H! Y
- } else {4 r# |& b3 H7 h) {! t
- alert("Your browser does not support Websockets. (Use Chrome)");
/ P) y# l! ]3 ], D8 V6 F4 u - }' e" C3 u t' c: ?% D
& r4 R' G, t8 o- `. z0 a# \0 r- function send(message) {/ a" P- }- \9 Q. M/ I4 {; F9 O
- if (!window.WebSocket) {
/ q0 P2 R+ O" d% c: x9 g2 @ - return;5 b. ~4 `) M1 g9 h" b
- }6 u4 g9 v9 g: q- D: S
- if (socket.readyState == WebSocket.OPEN) {
# i$ H: Y: P- A2 k* {0 L - socket.send(message);1 x! ^+ W% e ^. h
- } else {! ~; K7 P( D4 d" d3 Q5 J
- alert("The socket is not open.");
" V% p7 v$ D: m3 y; Q- u - }
0 ?# f5 `0 r5 q; z - }1 l5 [6 H* m$ O R
- </script>
( K! P: i. A9 F4 n - </html>
复制代码 ) Q0 P$ e" [$ X
* T2 s8 K+ g' ?7 Q' d. @ c3 [1 @ ^9 f6 Q* d/ H3 D' X
|