如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码
1 [, A4 \7 a, G3 j& }1 ^! T与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
% C5 {: F; ]) K
# T: S* k2 H# y. T9 u
9 r/ y- S* ~. T该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开
' _1 t$ Q z9 I( Y - }3 Y$ f8 a" _ L) f# j
- # j: O) S" Z' v2 U& G# }% ^/ h
- socket.onmessage = function(){
2 @" J8 i% S" }3 S% ? - //在event.data消息数据1 s& D! @7 ^; P) U; e& J
- }
8 { t1 }+ M$ W5 o
" N/ @; n' R$ V5 y6 }9 r- socket.onclose = function(){6 q8 n8 d2 p: V, l
- //关闭WebSocket
: c; }3 E( q3 e - }# q) j! ^; D9 G9 k
- 5 H& {# O5 }& T9 b
- socket.onerror = function(){
v: Y, D, W7 ?$ V( O# O3 e - //错误触发
& Q d& q7 U8 A( Z* ]- Q - }
复制代码
# s+ ?" T" V; T8 W, i+ }
2 L4 M( F: j; A$ G通过套接口发送数据,调用socket.send: 1 H7 T; v* p$ O) X/ p, R6 y8 i
" I4 {7 ]" O! U Z0 q( D! Q* Y+ b6 |8 c3 I, H3 v7 p
代码附上: - <!DOCTYPE html><html>
, H. g3 W0 }3 }" ^( |2 U i, \ - <head>" n: F( n: C! q0 y! L3 m6 @' G
- <meta charset="UTF-8">. b/ \! q, f# ?0 O/ H0 {1 B i
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
3 k7 O& l7 j4 N3 ^ - <title>WebSocket</title>
" O0 a. Q, I ] - </head>
. M+ h; E( \( z! S' |0 b. O+ X - <body>
/ D) i- \; E' F( c - </body>! k4 Z3 `, t: L% I
- <script>
; n. x2 z" `, r* C. n) F0 v' }+ r! P - var socket;
) a3 C% L+ n; F; c( T - if (window.WebSocket) {$ P- a' |8 S7 y! O$ T
- socket = new WebSocket("ws://localhost:8080/myapp");$ _9 y* r, X6 z# i/ q# ?" B
- socket.onmessage = function(event) { ^% _ w$ f2 U% h* `) r
- alert("Received data from websocket: " + event.data);) Y/ x4 k) I8 t
- }
' i. T4 D; S3 B4 M - socket.onopen = function(event) {3 s6 [, ^9 J7 |: l
- alert("Web Socket opened!");$ B+ w- z8 g- _- E7 T; M
- };
/ ?# K; c9 I1 P. V/ w! h2 [- _ - socket.onclose = function(event) {
! A" {- J6 o# Q- O! }9 x - alert("Web Socket closed.");$ f) L5 G/ C: B' B- E- Z. P8 a% Q
- };
0 _! a, J; T- W8 s+ f1 c - } else {
+ x" f' O) r# A8 M3 d! L - alert("Your browser does not support Websockets. (Use Chrome)");5 [9 T5 F& T; G Q Y, z
- }
2 e/ ]6 g- Z$ { - + e* E0 n8 q- Q0 m% X! f5 ~
- function send(message) {, N) c% W4 E- D( _' C
- if (!window.WebSocket) {
6 G+ w1 a+ N1 T/ Q& g1 c - return;0 a9 ?: ^' B( i% f. P- m
- }, _& k+ m& ~) v- }1 e
- if (socket.readyState == WebSocket.OPEN) {2 V3 e k) x4 L- n9 N* X& \
- socket.send(message);
$ Z' q; S; g- G: R N" ` - } else {
3 F$ H6 x! J8 [' \) \5 _; w - alert("The socket is not open.");
) p( R+ M+ `& { - }7 ^ q6 n4 Z! m/ P
- }' }6 j: ^: H* P2 r# \; |
- </script>1 C: L; j8 o3 Q9 u# i7 {: {
- </html>
复制代码
. g6 L1 y- d6 L. ~/ _: ~$ Y+ o/ g/ t& E
- L! C1 P% a% [& y) {9 T0 e
|