如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码
: O# j; t7 z0 W+ P$ u" C# {$ k( Z w与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
. ?( p E& S% t1 a: o' u& }! b0 \$ o, s1 }9 D
9 p$ F n' m o' j$ t7 v$ N该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开
) x) M9 K! y* c - }
/ ]3 Y _% O0 K6 d
7 v9 m7 K3 c2 ]# D# U- a- socket.onmessage = function(){" a' n/ r x9 M. @# N
- //在event.data消息数据
3 K/ u4 g* s$ z; B( Q& V - }
$ K4 D4 h9 I" N `7 e# n' { - * p5 ~- B, X) B9 @) E {
- socket.onclose = function(){% u5 q# z$ M! L
- //关闭WebSocket: }8 r n; v- ]6 A( o, u' U
- }2 J- j W1 o6 R" G
' [8 w2 N+ b, ~0 x3 ~" Y- socket.onerror = function(){
( o* J/ E4 _3 { - //错误触发6 [, ?; [ s k9 }. n" r
- }
复制代码 / k& f# R4 L- s1 x% H% S
- k+ Q" C( h1 o+ a0 R% ~
通过套接口发送数据,调用socket.send:
' n" f& Q% m. f$ }9 A- y1 X K0 e/ E
l9 M; D( O0 R& y9 l代码附上: - <!DOCTYPE html><html>
; v, c9 B$ X" E$ E- M5 G" Z - <head> W ~/ [7 \7 m# J8 t5 ~
- <meta charset="UTF-8">6 e1 _/ X# f7 M b$ I& F, C
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
d! z/ [; V/ \( ?+ C2 P/ A! Z0 R' U - <title>WebSocket</title>
- c6 x p3 ^0 T; X' _& H - </head>
4 {+ t2 h M) O - <body>
2 O( D3 j# ?/ ~) o - </body>: W- d/ |& e& k- b; d/ o
- <script>
- x. O$ ^4 X2 K4 q7 X - var socket;
% N# _; F B6 m: Y; B5 R5 r - if (window.WebSocket) {
2 y4 k2 {: F8 l9 V: E6 o2 @' C - socket = new WebSocket("ws://localhost:8080/myapp");
! u6 t& d8 |. [ ?0 T! h. y/ G _ - socket.onmessage = function(event) {. [) Z7 x# u5 ?' J, r5 x
- alert("Received data from websocket: " + event.data);! x% b3 v% n" S
- }, N* G* X$ g& b' j2 p; F1 C
- socket.onopen = function(event) {7 w' E3 t8 u4 k
- alert("Web Socket opened!");
8 _0 ~( g9 S% C p, ~6 J - };/ O0 R# v4 V8 M; L4 b
- socket.onclose = function(event) {
* e m7 N. E2 ?6 n% G+ r - alert("Web Socket closed.");
- ]4 A( ]; a- a5 ] - };+ e5 U3 m" l1 ~" H/ ~& w
- } else {
; v1 I$ J) Z5 H, R7 B' K. s8 V - alert("Your browser does not support Websockets. (Use Chrome)");. D8 I5 x& G' M u& S6 V* a. g/ C4 u
- }' y# Z7 C$ J* I, O9 Z( z7 ^
- . s0 }9 ?5 k x, E5 J! N
- function send(message) {
$ Q; G: U( M% ] - if (!window.WebSocket) {
4 A- z# s4 {: Y {0 j% [ - return;
2 \4 T" t A. m [ - }
. K' L% z$ i2 |' R% l2 O4 L+ m4 L - if (socket.readyState == WebSocket.OPEN) {! |, ~8 `' c1 x, h* A! i5 l. ~
- socket.send(message);$ R6 S; C1 J) Z0 v
- } else {9 _1 ~. D: `4 R
- alert("The socket is not open.");* ?& T4 m2 [+ b: E6 o
- }7 e5 a. N" Z3 e
- }. [; Z; F, {5 Z$ g- \: z8 [' T
- </script>; }) ?6 c' w8 y* ~* g; {8 R' t
- </html>
复制代码
! a8 q' ?) W8 Z
, K- g, Z D! [/ h: V# E5 {9 A
8 \3 T C8 n$ m' q' \ |