如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码
- T, l& @) V) Q7 ?) ]2 D与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
4 k5 @1 M, Q( }6 x/ L
; T) k. K; K% z: N, |! D A
+ c6 Q. r: p( o1 v1 @8 w( {) p+ e该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开
+ S z# R+ a8 E( r2 |' u4 Y - }2 j/ b" o, T" e# e! x N; k$ T) b
- & w( H/ k) k6 Q, U2 U) c! ^; i
- socket.onmessage = function(){# N+ W. C" E8 Q
- //在event.data消息数据: B, r$ {' Q) j6 o, C
- }, u6 q: c2 W/ r# |
0 b" D# |8 Z( ~& N4 _. d- socket.onclose = function(){5 @5 `' f+ Q. `
- //关闭WebSocket& ~. r3 o1 x) O# p4 B
- }( ^8 _: y, w. P, K, }
- % b5 z+ u D, s7 u; w# j
- socket.onerror = function(){
! E' w/ ^# B- `+ d& H& B+ B( _ - //错误触发' [2 g* L& [( ]4 D( W9 l, d
- }
复制代码
9 a0 y) `- X$ \# x4 ^8 ~4 p& y( z5 {* K( Z
通过套接口发送数据,调用socket.send: . q! x+ ]8 Y K) i. ~
/ N; }. D! k8 h+ d" b1 p, h2 F
7 U8 g( S0 L0 P( v, N: |3 f9 U2 W" R4 g
代码附上: - <!DOCTYPE html><html>5 P; a/ `7 F/ Z/ @ p
- <head>
" J/ _' w0 U0 G, I: v/ i; l" b- z - <meta charset="UTF-8">& Y$ H) n `5 V, a/ M0 ^+ L
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
* {) S! R0 G, T4 J4 { - <title>WebSocket</title>. G/ \2 y: G# T, \/ r1 e
- </head>
0 a2 w. V) W/ Z - <body>! o F) e' |7 C5 V- w+ @2 v
- </body>
0 K% c6 \( B5 k- { - <script>
0 b0 P/ F- N0 R% Z - var socket;
) r( u: O/ v, B; D$ z - if (window.WebSocket) {9 V) Q( ]: M. e" u/ r& {
- socket = new WebSocket("ws://localhost:8080/myapp");5 D. U9 B0 ]9 F) L/ x7 b
- socket.onmessage = function(event) {
$ h6 t( e( ]- I9 E - alert("Received data from websocket: " + event.data);' y% ^1 E, `1 e, g: e# e
- }
, {* W* M+ u2 }" W# O, B - socket.onopen = function(event) {
6 v3 s' P6 ?! e: u' t" E# j1 I1 \ - alert("Web Socket opened!");
; `4 {8 j& c% ?1 ?0 K4 P - };
( M+ s' r5 U' Y' ~" U - socket.onclose = function(event) {) B( D& \, I3 M/ X
- alert("Web Socket closed.");7 y+ U$ e' r; o; x, J+ k( V- J2 }
- };0 a+ k% U8 ^( W% X3 a% c$ p! p- x
- } else {9 z" z ?8 A0 C" T
- alert("Your browser does not support Websockets. (Use Chrome)");3 J5 v8 |& B0 {8 h3 |9 Y2 k3 r
- }
( o8 G4 n( w7 K: y7 u: \
1 W! v+ m2 S$ W! f; `- function send(message) {
1 o. c1 m+ {0 w$ o/ x# H9 ~5 Z# L - if (!window.WebSocket) {) L) `9 K. M9 V8 j1 O0 \$ k
- return;) G: F& [5 g' W$ f$ S. d
- }; [2 E3 H3 S4 p) b3 H! g
- if (socket.readyState == WebSocket.OPEN) {, Z( z1 s" ^8 ]$ R2 b
- socket.send(message);, M$ W2 W- C2 Q7 a0 q4 i6 p9 T0 v
- } else {
' H+ L2 S0 e& K - alert("The socket is not open.");" U% K4 [4 U" b. K7 n8 C: a
- }9 a9 e5 P4 x2 h, y9 ?
- }
4 l4 [3 ?9 M/ F( g! Z - </script>
- u* D$ ^5 F% d7 a - </html>
复制代码
# V; x6 M* Z+ ~0 \" y
4 \0 }. J: h& R& n* f2 u
1 ]" T9 D# g( x. R& B |