如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 % E( G# r. F( k0 s; h9 b e9 X
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 3 n& u3 b+ `9 H( `1 C$ N
. b; U+ A8 k3 B2 Y$ G2 K" B& t- P* e
! x% ]* z& ] l/ M8 f) ]7 y' T
该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开3 X' w# l; g& [! G+ ^4 R4 ~
- }
8 r; _$ Z B4 k" q" o
" B. w3 M' P s6 N5 ]- socket.onmessage = function(){, a; H. r5 l' D4 `' _- C
- //在event.data消息数据8 |. ?$ h4 f4 V( T5 k1 M/ q
- }
; Q \( F# k# K) ~9 a; t) F
* @+ i) R& d/ t9 v3 Z- socket.onclose = function(){
- R5 Y- P; N3 g. J0 @7 _: z - //关闭WebSocket
% }$ T: c0 R' b - }9 H+ b" G+ C. j, z* E" _
- 2 p, m1 J- m8 k3 ]7 {
- socket.onerror = function(){
' j: ?3 G" C- }& D- k4 z - //错误触发
! ~: o/ h% w9 e% h8 P1 H! }# I - }
复制代码 * B: V9 W+ ?! q2 E- c* P
; ~' F& p* P5 d! s: y通过套接口发送数据,调用socket.send:
4 S& R" ?$ k, J3 S! y
" W6 G) D R; e, s4 O" u+ u) K% \/ i4 b6 s% V5 \. C# ~: V
代码附上: - <!DOCTYPE html><html>
0 B: x* ~. J/ l/ m9 R, D6 K: P# h - <head>
- M# E* ]" J# z4 b1 V8 k - <meta charset="UTF-8">6 j1 d4 o% |, O) J3 U/ B% I! \5 T e' I
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">$ C3 C% ?. }: B: L
- <title>WebSocket</title>
* \" B2 P) h! N" L5 { - </head>6 I ?. _7 v! L* O( K$ \& q
- <body>7 l/ q9 ?& ^& q8 |, S- X
- </body>4 U# O7 [1 ^6 e& O# P$ X8 k+ e7 N
- <script>+ h5 V* s7 e. G0 Y
- var socket;0 H0 h# @2 J" Z" ~& c
- if (window.WebSocket) {
! n3 {& w* {' `4 v8 }& i% I7 F - socket = new WebSocket("ws://localhost:8080/myapp");# v. L$ C7 b$ d8 A0 {* k
- socket.onmessage = function(event) {
: @) g6 ^9 r- J g" F# `3 L/ w - alert("Received data from websocket: " + event.data);' F. a! F# N0 W. q
- }/ Q, p, n% U- ?7 s: @0 ^: C* w
- socket.onopen = function(event) {0 @0 v2 r/ K9 l; U
- alert("Web Socket opened!");
- y: x9 J# `3 q - };
; F9 p; }- J: s: D" Y2 s w" @0 e - socket.onclose = function(event) {/ O% v$ v# F% q3 r
- alert("Web Socket closed.");1 x2 N* X# K/ B @$ J( g
- };3 j% N4 G7 U: D) [) S
- } else {8 f4 ]# l& B1 j& g9 V3 U
- alert("Your browser does not support Websockets. (Use Chrome)");) u6 b& b) z/ N; ^7 h, ?6 m8 y
- }
& R% D6 O) X6 ^- E7 |8 \+ b; ^
3 g1 S4 y1 G0 b' a- function send(message) {
2 W" [0 Y3 ~5 Y3 P) F& }+ c' O - if (!window.WebSocket) {7 H4 Q! }, N+ h% H% h
- return;; } r( n/ ~: V5 P; y# c
- }* H- o7 d' H. M. s; v% N$ G) g
- if (socket.readyState == WebSocket.OPEN) {( U/ z3 O; u' g& U
- socket.send(message);
( R# s- U* W- q, O1 ]( l- ]0 T - } else {
) W Q: D7 F; J# r+ A - alert("The socket is not open.");. y/ q7 q3 L c$ f
- }
1 H; f7 y; a/ o0 A, h% S( v4 g5 X - }7 q! ^. b+ Q5 S1 B. W: ^" @. O
- </script>
' _( M3 d1 d0 U! V! p+ f0 k% [ - </html>
复制代码
3 }& e$ P- q$ e& o; L- T1 C% m7 j) X. r- Q4 l$ q" `5 Z
7 h1 d7 r0 h- P% i* N: F: K |