如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码
- X t' k: X$ Y与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
4 G& L, Q- X+ _4 A8 f1 q. H# r) ]4 d, Y: \: j9 r) _
2 i6 h1 C/ S- n; \, O该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开
% w0 m6 u; ?) q1 ~* o - }9 ^ u4 K1 m3 t: ~' K! |& H
' S( ]& D- ]- T T* S) e0 _+ U3 o- socket.onmessage = function(){
+ E' S" O, W' e# a6 |. p0 D8 f6 G - //在event.data消息数据9 \& l% Q2 d4 ^* Q
- }1 z" D, `4 ?! Y; e5 l6 l, F
0 J" d3 T$ m) ]+ G# n& W- socket.onclose = function(){) i' \3 F- [5 x3 u9 t9 G
- //关闭WebSocket$ w0 {$ {: ]9 ]+ N% E; a% f
- }
Z- u# c9 p, `$ F# K6 e& y - , e8 p) Y, `& o* @9 K
- socket.onerror = function(){
. T4 r9 X) \& q' y- o- E - //错误触发& y7 [) @0 F- t$ g! r- b4 Y2 _
- }
复制代码
, G3 ?+ |+ p" R3 M0 C8 V2 E+ b6 B6 P6 f
通过套接口发送数据,调用socket.send: # a3 k" g9 _, A
2 f5 q" t ?8 ~. i: R2 Q( ?$ G9 P4 C$ [+ z" N# J
代码附上: - <!DOCTYPE html><html>5 A# g( G! k; X- b
- <head>
7 `! {, |1 }# x% y4 R" ?2 @ - <meta charset="UTF-8">' g5 L d5 h7 C* j" ~$ `7 W7 X
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">- t6 U; W8 j3 h$ _6 U3 t' |
- <title>WebSocket</title>
8 j: r5 l/ m- ?6 I2 K1 v - </head>) B! r" L! o0 V
- <body>
1 D r4 v& s, u0 t* v7 X0 x - </body>
& @ \2 Y0 I& S - <script>! V, K6 V; w& Y; k, ^( s+ r3 e* c
- var socket;
4 D2 Q& `) U5 E0 ^8 B# ~- t - if (window.WebSocket) {, E# j x8 ?1 G# ~' L6 l$ L
- socket = new WebSocket("ws://localhost:8080/myapp");
) _4 |% x- r# s2 y& L1 P - socket.onmessage = function(event) {
& h6 p3 ?" `6 V+ H4 G" b' ] - alert("Received data from websocket: " + event.data);
# K- L. c: G- w2 t - }
- J) a$ i( w! w6 G4 L2 b! \# ` - socket.onopen = function(event) {8 {. a; g3 W# c; }
- alert("Web Socket opened!");
- z; p# ]# O+ K2 x - };7 W# ^5 [( I- E+ T! i! \
- socket.onclose = function(event) {
- j* Z- W) N) ~. l# o0 z, W. i2 Z - alert("Web Socket closed.");; ?6 \) `) E( _" O' g! [
- };
8 Y. o1 K# ~& F2 o6 e F, l8 g/ e - } else {% m0 H8 }$ A8 U$ o& @$ {
- alert("Your browser does not support Websockets. (Use Chrome)");* M! v; H; C2 ^/ S8 ~' K# n# Z
- } j1 @' ]$ j5 P( H: F v
0 J) ]6 `2 g) a6 `9 w" F& n- function send(message) {
7 `! `$ s; A! A y9 I3 w% f9 c# Z3 I8 [ - if (!window.WebSocket) {0 ~; {/ w4 e- W* J9 |% N
- return;
@6 s/ U( [6 Z D: X - } q( P" o2 x+ |1 W8 Z
- if (socket.readyState == WebSocket.OPEN) {! z( r6 |9 v) E' h
- socket.send(message);
6 L" Y' Y, E) X0 r - } else {
* n4 C6 b$ u f! L% o' T - alert("The socket is not open.");
& q* y: O% z) H9 k; L - }
$ A# a, o5 j& q+ e5 T% g" T - }
8 @. l8 o |% m. B) s) h0 T6 g - </script>/ P h% c: b) A# f7 i# \5 K* ]
- </html>
复制代码
% H/ p& W. g0 Q6 s7 @8 k& L0 x F$ s5 |8 O
$ J% R( ~$ d9 ]' x
|