如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 * @" p# N5 y. K9 _: V" ~ K" Q f
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 7 M! y+ ]1 ^5 n/ N# C
" h9 L( V6 C4 |: y- x8 ]
4 Y$ s8 @1 f4 i* N4 H) v3 E6 J该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开, z$ K4 I2 B* e E
- }& q- }: |1 G: _. A" S3 O7 {& ~- E
- 9 h' j3 M+ D6 l- O t+ `6 O5 ]
- socket.onmessage = function(){
z# d! \, M5 { - //在event.data消息数据" k4 y c! Q: a i1 W i
- }* B3 Y* p1 {) l4 g
% U; ]7 M7 _" T: |( |/ `4 v& q, X6 i- socket.onclose = function(){
* k7 E" F7 g0 d0 n7 k3 ]9 P( ~ - //关闭WebSocket; L# Z+ c$ ^- c3 A
- }& w$ G8 X7 ^, [- I
4 P' P) I% H6 {- socket.onerror = function(){& T0 l6 C- Q6 }; [7 v2 @
- //错误触发
. s4 M5 w$ F6 S8 V& N& d) h - }
复制代码 # k6 X. e' M% [6 M U+ z; y a
2 A( [$ o7 d4 G& d$ Y, f通过套接口发送数据,调用socket.send:
; G, t t& a+ `1 \( e& j' K" L1 T% @( V4 P
4 r5 D7 L! T* ]$ l; Q
代码附上: - <!DOCTYPE html><html>
; ?$ }; p! J" ^0 ^4 q - <head>+ q; m- n& R+ D4 `1 r% ?% ~# `
- <meta charset="UTF-8">' V+ G+ J4 {$ H! D
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
/ z& o, @* s/ Z - <title>WebSocket</title> z7 }7 `2 A2 F# ~
- </head>
5 Z4 S( I7 @* v, g/ F' I4 }* a6 n - <body>; @! B5 p3 ]8 ?! G
- </body>
8 |# S2 ~* Q8 g3 r% m# B7 z+ i - <script>1 A% ^4 A- \2 w- [
- var socket;
8 Q: f9 E$ P% ?. F$ `3 S1 t) g- | - if (window.WebSocket) {0 e& _, n4 J5 N) Z3 I
- socket = new WebSocket("ws://localhost:8080/myapp");% P) Q' r; _+ g5 T- c
- socket.onmessage = function(event) {
: n8 F3 S# f4 w0 K; P. R - alert("Received data from websocket: " + event.data);4 K# i$ h3 B4 H) Z
- }: `2 `( M7 b. q9 p% k( E" Z% J
- socket.onopen = function(event) {. A; S2 O5 Q: w4 U4 Y+ {' A
- alert("Web Socket opened!");
a( X$ L2 Y( w, s4 l - };
, n4 L* Z3 L: b2 W - socket.onclose = function(event) {0 t2 M+ G3 N6 v& g
- alert("Web Socket closed.");
0 h# b" w6 w9 \4 h3 x: m - };
: M0 p% A& p" c; Y% k5 _* T S - } else {, A( l5 z: |" ^9 L0 y, \9 s6 u" H
- alert("Your browser does not support Websockets. (Use Chrome)");
. i( b1 C8 V5 F3 P - }4 y' V- `' h) D1 l4 z! t6 K! e
- 2 d0 v6 e) w* F! {3 u( M3 _! m
- function send(message) {' d0 `) [) _4 n. W
- if (!window.WebSocket) {0 J" {3 }" H0 k0 ]) f
- return;
3 s+ o7 q! S/ {% Q1 A+ n* K p9 W - }" l5 I4 I& K/ u- J3 K' N0 h
- if (socket.readyState == WebSocket.OPEN) {
% k9 [8 Q/ b9 ^1 c - socket.send(message);4 d/ V( h1 x) G1 B: z k
- } else {% m; Z6 H5 e s& b. }
- alert("The socket is not open.");
3 X* l# _7 \6 m8 C7 x - }1 _& F/ i1 m' ?0 Q, t7 d, d
- }& F& ~; f% [( h
- </script>
4 r A0 o3 q6 H9 \, r h - </html>
复制代码 + ?' W2 O. s2 Z- P6 W
7 _8 O5 N b/ U: o! I; b8 B4 b
( K; V7 E1 ^1 X6 P8 A1 m& A5 { |