如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 # k9 C/ a* r/ ?4 L. u x/ E/ P6 ^
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
/ L- E6 w E) [8 T' L @, j) F
5 g; J; ?3 c3 S( G/ I
$ U$ N9 a, `. L( `3 O e该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开9 B; R" N9 g( F$ P4 r
- }4 x6 U2 M3 U. w1 e7 J7 m
2 n" z% V" j/ I8 I! O$ k; U. q- socket.onmessage = function(){
& W) {( e% Z. E6 P2 O1 W# y: Z j - //在event.data消息数据/ N' \/ e# @( ^4 z2 m7 N) S$ [
- }
# @, _$ ^: J0 c2 P$ U4 G# A - ; `; n9 S' ~. k2 V2 J0 c, h5 h8 h
- socket.onclose = function(){! M' K7 H/ Q- L% w$ z
- //关闭WebSocket2 b5 U' o5 ?. b$ y' @: ]
- }/ @+ R7 N: U! _3 ^1 D9 _; c/ U% O3 T
) k" q; y4 t- ~9 d+ x4 I# `; s- socket.onerror = function(){1 ]# A8 s. o3 N( w4 Y
- //错误触发
8 G4 Q6 u! S. t* p2 l1 R* @3 `0 q# s - }
复制代码 " w9 K3 d# M i: U P
. ?7 E2 z5 A) q2 a f通过套接口发送数据,调用socket.send: * o, P+ f. p0 E/ u2 T7 ]
0 A( e) p% ?9 j! x: H% } M* z
% g7 O- E1 U- c0 X' D8 p+ O代码附上: - <!DOCTYPE html><html>9 S- ?7 C: X @! ?
- <head>) ~9 K) Y! W% w9 k0 o4 I; W1 a0 s& h' j
- <meta charset="UTF-8">9 `0 O6 J4 m- u. w a; S
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
Q9 x( K0 j- d; ?) F3 C( k* c - <title>WebSocket</title>* H* R, C) n1 B' }: n p
- </head>
$ A0 `5 V5 M1 l O5 S4 u- y; x - <body>
) n7 a0 T ~' _5 b8 Y" q - </body>3 y, q% y, }' p- p" T* D
- <script>
) f7 Z& a9 p& L& ?9 y3 q9 I - var socket;: t+ X/ i) N7 S/ i. s- d
- if (window.WebSocket) {
: [5 ?- t9 F0 y* ~* m$ T3 Q - socket = new WebSocket("ws://localhost:8080/myapp");" G, u7 S. u# P! x* |
- socket.onmessage = function(event) {
1 V& a2 ^. U0 E! S3 S; O- L# x - alert("Received data from websocket: " + event.data);
" L, ?$ P3 j# t: l - }
. n+ \( P4 E D3 ?. J - socket.onopen = function(event) {4 C! E/ `& U! u2 w
- alert("Web Socket opened!");
, d0 A. ?6 H1 k9 e - };3 d6 O" L6 ]) z% P
- socket.onclose = function(event) {
: l! `. ^3 L1 h! D3 T. a+ e6 a9 y - alert("Web Socket closed.");
2 F, i& X! N6 z% L! C" T; ? - };& {0 u; f5 ~7 }
- } else {
# Q* {' X9 R5 L1 p# q- U7 Q - alert("Your browser does not support Websockets. (Use Chrome)");% r, B$ d" ?9 K0 C3 f; w; B9 \/ H
- }1 K: x' a" Z- K
- 8 M# o# H- @0 s; l2 ^! j; {
- function send(message) {2 a- d8 \( w( d2 x* T
- if (!window.WebSocket) {
8 v5 I6 i U1 ^& e8 B+ B- a - return;, l* m8 s$ s( a+ S. F) M
- }
8 O$ G! |$ f) m a3 Y3 g, q - if (socket.readyState == WebSocket.OPEN) {
% c- z7 }$ J2 M4 \1 x/ W, B6 Y - socket.send(message);2 E! F5 s5 a) Y
- } else {* q2 B* }. \% I2 _9 y1 N, M
- alert("The socket is not open.");
1 }2 |8 v$ q8 x7 I. M i3 a - }
# }& f* L. `9 M* i- D8 z8 M - }
/ h2 h% ~/ {5 e - </script>2 w" W# m0 s8 }% } r# e
- </html>
复制代码
8 m7 F" I& X: B. z# F( O8 @ ^2 l( K# O/ [) O
. I8 u3 Z) v L |