如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 ' b5 H( Z5 I& [! ?1 @: k8 K
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
* {- ]9 E- ~' Y* R6 Q9 e
8 |7 z: Q5 ~! p# X0 o: Z) A9 o! N7 g' `$ P
该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开
( ]' C8 d' o7 U# v) ^: v; h ] - }3 \- ^, C" Z8 y6 Q4 [
- ! k+ P& W* |* g1 ^' E
- socket.onmessage = function(){$ h& Q' s5 D9 ^& i
- //在event.data消息数据. N; W; \! W" T0 ?+ Z {' Z
- }/ y- k9 @: c+ w: w [
. C; h) l: c; L0 Q4 G2 I, k- socket.onclose = function(){
1 U2 M7 q# X: z5 ~ - //关闭WebSocket6 {/ N0 ^+ Y8 v7 |* d2 `6 f
- }( Z6 b3 t1 n/ Q% P: J
* p( @! t2 |7 r% ^% @- socket.onerror = function(){* {- w3 k* h% F6 K, G$ Z) v
- //错误触发$ U8 E/ s' Y+ P) g/ ?+ [
- }
复制代码 , m( X0 n* B- H/ |8 w( R: v
Y" E0 V0 ^" H N. g3 r通过套接口发送数据,调用socket.send:
R' h( ^* g8 h7 u" q, ^
9 Q0 ?, k r3 F- g' `% ]$ Z9 b) m
% N) I4 H) P8 j* T% B9 O# x1 u2 K3 R代码附上: - <!DOCTYPE html><html>; e! }7 P; K/ _' F7 _) j, j; v
- <head>
' f$ ~* C/ a) X - <meta charset="UTF-8">
$ a0 @. W7 v" _3 q( }8 ?. \/ Z) C6 i2 o - <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
& k$ h: q" b: v, Z. y2 ~ { - <title>WebSocket</title>
1 O. i- e* w" w' Q - </head>
1 c. t. T4 ~, m m3 ^ w - <body>& I- _8 m* y5 H$ R( q
- </body>% b& z% _. w* S# i
- <script>
+ N: q L+ D; h) O0 N, f- ~+ B - var socket;
) h2 G' T' A7 |5 r, c& p9 K - if (window.WebSocket) {
+ \2 l7 V0 t% t S% q3 o - socket = new WebSocket("ws://localhost:8080/myapp");/ H+ |/ {3 V( A- Q" i
- socket.onmessage = function(event) {
2 l* ~- y0 v% J" M$ X) { - alert("Received data from websocket: " + event.data);
. c8 G/ d8 w; M5 g8 [; N1 F - }
* ^# p, y" R* K G" W# B2 Y - socket.onopen = function(event) {# {& S9 `) k8 R" L. }$ h5 O5 L0 h! g
- alert("Web Socket opened!");
4 U' ^2 U/ I) r6 x1 g3 l - };' ?; w/ h: h2 c
- socket.onclose = function(event) {
' g+ _# e! N4 t0 g4 Q0 ?8 B9 ~ - alert("Web Socket closed.");
" B9 i7 T. i+ g3 Y# I - };
, g7 T/ G0 b6 M& O8 d! Z7 d) }8 O - } else {
6 y( }0 W: v* [: W( u; r5 \9 u - alert("Your browser does not support Websockets. (Use Chrome)");
1 a9 f+ C, j$ h, f" c' e - }: c+ z" A6 w7 M- v- e
- 4 H* N" F e6 h
- function send(message) {
' b& e3 ?4 U% S, N0 I5 b - if (!window.WebSocket) {2 O( L+ ^- K* \
- return;
2 U+ a( v( n* P3 Z - }
( }, q9 y8 j7 _- P1 Z( M - if (socket.readyState == WebSocket.OPEN) {
+ K6 J3 u9 H- ~" L! q0 \ - socket.send(message);
) E+ ]( @. r* V6 t, l - } else {( j/ I/ Z7 X' O5 A
- alert("The socket is not open.");
) r: p8 }. A- k/ e& ?( @2 D - }( {6 k( |) N7 S: A5 X4 ^7 N% I
- }
+ [0 G* E0 Q1 [* r - </script># x5 U) E+ r% g/ K# ?3 T
- </html>
复制代码 & K( p9 U9 j! [8 Z3 J" s2 j& i
* U, z+ y9 O, _2 g9 }3 b& U, l6 g$ A/ S \) i( x3 A1 X4 [, n, G
|