如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 * F. c0 U7 [8 G( L
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 ' ~: q V+ D9 m
. U" x; s0 P5 L6 \: T2 S# _) V, c% `
# }1 Z% L; [$ _) W) N% _( Z
该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开
4 p; m( [0 G" g& H - }
& u7 o' M! t3 J* X$ @# Y9 h2 Z - ' ~! @+ c6 V7 N3 \
- socket.onmessage = function(){+ ]: Z$ v: u; l$ E' A4 M x
- //在event.data消息数据, l: b, [% ]6 y5 ?5 K% q X
- }! _8 G/ U! x6 X0 Z i8 Y
5 S; @2 h, c; x K# V1 r4 {; D- socket.onclose = function(){6 O( `2 n2 D& Y+ f
- //关闭WebSocket
$ L2 g$ P) F l! Y) Y, W0 D - }
4 z9 A" \. t: U# f8 v
2 s: L% ~( S; W0 _$ F" ?5 s* \- socket.onerror = function(){) p5 X* t1 V7 |. e5 c
- //错误触发& g. [1 ?! W: J# T/ o" d: Z
- }
复制代码 ( @2 d5 o$ i1 {$ _* q
, {: q- ~ E3 G( B* n% A5 B通过套接口发送数据,调用socket.send:
, ~# t& E s2 j# r% A
' y; B, W8 l6 m3 ?1 S* ]9 N# g8 _
+ d0 q( c0 O* N1 `9 c \+ K代码附上: - <!DOCTYPE html><html>
: {6 f- m5 P" g - <head>
8 t2 G. J2 L" c: o - <meta charset="UTF-8"> f. N7 {' j" f; S x- D
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
% J) t. Q; X5 u8 P% S) d( J2 y - <title>WebSocket</title>
. T' R. ?. R' [- `1 u+ l9 ~- r - </head>
1 T% D, M* H/ R5 o6 L: ]- n+ a - <body>
! o" f& d5 J7 Q% r; j9 B7 A - </body>; W3 Y; _) |2 O m4 M
- <script>) b1 B6 @3 p. M O: T
- var socket;( F. h& s3 g6 t8 i
- if (window.WebSocket) {
6 f g. A: k P! ?& e4 E - socket = new WebSocket("ws://localhost:8080/myapp");
) }( g, I3 a- s8 |2 t* r. ? - socket.onmessage = function(event) {9 ~9 s4 x( A/ s4 H* H" o D
- alert("Received data from websocket: " + event.data);8 N! w& B% h) \0 ^5 n
- }# K2 w! O8 J6 L
- socket.onopen = function(event) {
* r+ a% y* L. d/ C - alert("Web Socket opened!");
+ f& T% w9 C; D) H+ Y/ u5 l6 A - };1 _" P. N' `% P8 H; H4 p
- socket.onclose = function(event) {- n! g/ z5 F+ Q9 L) H @
- alert("Web Socket closed.");
: D8 E! l) x( @2 Q - };7 E/ V9 J$ s; @: x% D9 t
- } else {9 u' u% g+ { T% B* }. z
- alert("Your browser does not support Websockets. (Use Chrome)");: j, U O& l4 E4 Z3 u. x
- }# `5 Y5 U9 K) \% j( E
7 B% I/ m0 E. m* N- function send(message) {
5 E2 P5 d) R0 i- _' H1 n, S - if (!window.WebSocket) { B) ?6 S0 Y! {' H$ c% s" |7 h
- return;
- }# o+ I; }& _% `& b* k0 p - }3 y- Y2 U, i! d2 y& O; B6 v
- if (socket.readyState == WebSocket.OPEN) {# u# v) v, \# L8 U- P# B$ x
- socket.send(message);
% z- l/ j8 ?8 y% z - } else {2 w) u' H1 W4 I% h( a
- alert("The socket is not open.");
( r3 @% y0 j' T$ z - }* Z, w3 x9 d( t( @0 h
- }& q& k7 V0 e+ y
- </script>
7 I6 n8 `' Y/ k - </html>
复制代码 0 y# z: Y" j: U4 w; }" R
* n2 q4 J$ e! |6 O0 t
4 ?" f3 _3 ^+ v1 t- Z |