如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码
# z: h: T' I% v6 i3 A+ W% v与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 6 d, r" j- x' c) U
. I; L5 v( D; p1 c5 I# r, b0 ~/ [
- t B: I8 b! ~5 p该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开
X+ W0 G6 x" P - }) M4 ]; ?, T( [/ a. D
- / ?# Y( u' K! c0 y5 x. T* }. j6 }
- socket.onmessage = function(){
6 z7 o% g* y3 q0 F5 X2 \, p p - //在event.data消息数据- l4 l. f8 i7 [4 @% f
- }
) e& u+ H" {8 g! J6 d
# v! x7 @9 g; H! g1 k- socket.onclose = function(){
; k8 \4 H$ y( w) s G$ B - //关闭WebSocket
! L# |1 u, G: s* j- v1 Z+ j5 \ - }
: Q- U2 T, q! L- ^9 r6 Y
' e. O, z4 }; F ?2 @, N- socket.onerror = function(){
9 j1 s5 R2 O9 ~) K/ ~% `% \ - //错误触发- _7 D9 P4 T; s
- }
复制代码
v2 Y5 o& b; Q' Y2 t) h6 Q; g+ k$ J
通过套接口发送数据,调用socket.send: 6 ?- h$ n2 p* r8 z; w3 n
$ H* o; ]8 w+ i' q- D+ W) Q3 `: T: S7 q# I
代码附上: - <!DOCTYPE html><html>4 ^7 I+ U& w8 e- t! Y6 K' m% Z$ e
- <head>
% u3 s9 l6 ]4 x1 W9 M0 Q, @ - <meta charset="UTF-8">
4 j4 _$ O- h: k7 a5 i2 ^/ B - <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
4 l2 `3 a j6 m) b+ f" W - <title>WebSocket</title>
3 K# l- s) N2 O1 g - </head>
1 F7 C. A; c7 d. m# O - <body>
6 ? K! Y* K# ?# d% B& g' ~! g - </body>
7 m; A, S9 _- ?/ d4 C6 {# @1 D - <script>
# H4 Y: G; p/ Q% C0 [( ^( V - var socket;( U2 k; W/ T3 K' k
- if (window.WebSocket) {
# {' n3 w- K2 d9 D2 o - socket = new WebSocket("ws://localhost:8080/myapp");; }: @+ Z, b" B3 k& ]4 Q( d
- socket.onmessage = function(event) {/ |( @6 x% F+ @7 }
- alert("Received data from websocket: " + event.data);
' f- y+ b; b4 T1 \- { - }: G$ v# u$ p1 `1 F9 m. R
- socket.onopen = function(event) {$ V2 G6 T d4 P* T8 T
- alert("Web Socket opened!");
( R2 b8 a6 z3 s4 _+ x - };5 m! T2 `4 ^) J! C6 Z1 o- w
- socket.onclose = function(event) {, M$ u& \1 |- U2 V
- alert("Web Socket closed.");
$ A. X5 ^3 I! c8 |/ [6 J1 K - };
. b/ i% c' C* e& ?. G# b( W9 U3 P - } else {
+ r( ]0 p" \2 U' k - alert("Your browser does not support Websockets. (Use Chrome)");
2 L! F N: f* f0 \& s5 C/ j - }
: S x; @$ M: i: U0 w
0 G0 a( P! i8 W- function send(message) {
( i/ K" ]# w G0 u! y. C - if (!window.WebSocket) {$ I2 |' l2 n6 U5 C9 ]
- return;& ?) t. _$ b/ V- A& W+ G: n
- }
1 ?: B( i" }! M0 n# t; p1 w - if (socket.readyState == WebSocket.OPEN) {/ M' |/ Z3 v: y$ I& q4 V3 d
- socket.send(message);- z. G1 e2 w ]- u l! T# k$ f
- } else {
, y" Q1 k$ m9 Q - alert("The socket is not open.");
5 M+ J3 J3 N% n" w8 A/ q' E1 {8 ` - }
: R) t7 ]: R' d( k- f! p7 @* H/ h - }& u- S L5 d6 x( V9 P, S
- </script>( o+ h8 y2 q6 J! U& D2 f' V
- </html>
复制代码
4 V# K2 k2 p% i& r9 _6 L3 ~ j# F Q
& M" `& S) a8 `9 O2 j4 }
|