如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 : y- ^' M7 ?/ p4 e9 y6 }
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
* p4 b; `+ G* e! P# L/ ~ e4 R% Y; T" z3 i) @7 U. M( x5 c' N
; Z1 Q9 v4 P. l3 X
该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开. j5 B0 _" x, Z% x' t5 S
- }0 v5 }/ n8 |* v% x
- # x. {9 n4 ?" T c: S; [
- socket.onmessage = function(){: B( a. K j7 q# i4 v9 G
- //在event.data消息数据6 }9 s9 `$ Z3 J* G' e
- }
; P* T3 w" T; D) z8 _
* [8 C5 A, k- B# B( V- socket.onclose = function(){
* s- o8 v/ a9 y& N( @. P - //关闭WebSocket
6 S$ B' e% b& }+ D7 `- d - }
+ m) X+ j2 h- f' ?+ V- } - 8 W# Z: W6 o5 R7 E/ B" q% Q
- socket.onerror = function(){
# V4 J; `2 ?" A3 u' g - //错误触发
4 q8 y& u2 h! K; @/ s' h - }
复制代码 - R% _/ P" C3 _* v0 m- F
3 T8 {6 W+ C$ J4 P通过套接口发送数据,调用socket.send: $ |0 B3 `( q& l! v
! o* s) }# U- D$ z" Y1 A
( H! y) [, x3 B% c代码附上: - <!DOCTYPE html><html>
, A2 X/ {6 m2 }2 C; k0 p; R - <head>
" E8 ]0 u1 m# K4 r7 D - <meta charset="UTF-8">) E2 j/ x3 L% F2 ], T
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
8 f* O3 ~ B/ r( u# `8 _ - <title>WebSocket</title>3 c O( S$ P$ Z9 V
- </head>+ ?. N" A3 a" ^! ]8 h+ C, }
- <body>
- x; v8 P; \0 A6 D5 | - </body>7 Z. r' f+ ~3 ?1 q2 b( b
- <script>
& [! p# O/ l8 [ - var socket;
; d1 u* y# J0 s& l7 @" A, d, u; r - if (window.WebSocket) {( p( I7 ^' Z! N- {. Z
- socket = new WebSocket("ws://localhost:8080/myapp");
$ v9 p* U _/ @ - socket.onmessage = function(event) {
/ G5 H g2 P, P% E U3 d0 l% ^( Z+ L - alert("Received data from websocket: " + event.data);
, v( g7 e6 {5 a6 Q6 n( v - }& H ?! v$ a$ ` H( i7 R% s' i
- socket.onopen = function(event) {
6 D) f4 L9 q; n& t8 C2 I* N; p - alert("Web Socket opened!");$ a( `9 U: u4 X! c
- };
/ G+ z9 W: Q+ r# Z7 i - socket.onclose = function(event) {3 M4 \+ R {* p6 U8 B! b/ ? I
- alert("Web Socket closed.");3 r! q6 _% Y/ d) _( t/ U
- };
. V, Y% a1 { ?8 R) g - } else {, @0 `' G3 x% [
- alert("Your browser does not support Websockets. (Use Chrome)");
, A8 t; O/ r7 F/ p* a, } - }
3 ^1 w2 J# l0 `3 }2 o( r! S- d
9 m; U! P1 U W. D, Q- function send(message) {
4 d: `: J7 q; I: w2 |* z5 V8 Q! a2 W0 O) j - if (!window.WebSocket) {
' t* u r( U" s: e7 ^$ P - return;
& P4 _# h C1 t- l/ j- Q - }
6 m: G9 I1 l: Y4 i/ p2 U - if (socket.readyState == WebSocket.OPEN) {
7 ]/ O4 e2 _1 T) _' V - socket.send(message);# B+ W* X- K; K1 m
- } else {
' y! ^( \, n. X3 d# c - alert("The socket is not open.");
- x6 B1 A! m1 M8 |. e7 c. U; c$ @ - }
# A3 F1 k Q& p( S0 }+ ?. [. n - }
# }0 K: R) @& C [; _ - </script>
T. j5 q+ i' {" x7 |4 n/ D* ^ - </html>
复制代码
" z" u( t4 M. o. D4 [
% d& Z0 {& h2 c: V; P4 B; q- r5 Q9 v8 W
|