如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 / [6 s" P4 K; x6 S9 ^6 ?0 b( n: E' o
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 9 `# m6 U4 r* ]
9 x& Y2 [+ T' _) @
1 l0 Z4 p- [3 E6 d7 H5 u
该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开3 R, K% \0 D4 X: ~) C( e
- }
8 D+ }7 P5 N! G# G
# q- C# k4 a' E- socket.onmessage = function(){
6 B1 a, O/ ^+ e7 P% c5 q - //在event.data消息数据4 J: c1 X" e, \" ]# s W
- }
9 U, y* U( f' T2 s - $ p* i/ _' f& A# ]
- socket.onclose = function(){
: i1 O; a S3 d( y3 [6 k |7 l, q - //关闭WebSocket, \6 u" e: S7 _9 k
- }
; k2 G% v; Z2 A: a9 n - 5 S8 q, S4 J4 q+ @1 h; O/ H$ ~
- socket.onerror = function(){
) D; w/ z8 v+ a- o" f+ D8 _' r - //错误触发
) s% ]- q0 z* k1 B - }
复制代码
# M1 T' _- F8 l' j0 G4 G. X4 ?' c& L- e0 I4 Q1 P( E
通过套接口发送数据,调用socket.send: # l( D+ ]) v+ j
4 I: F* U2 A4 }
9 q) m4 y+ n1 s4 ^
代码附上: - <!DOCTYPE html><html>9 B) D2 u. D1 y( k* `
- <head>. M' X/ q# r7 y8 v( _
- <meta charset="UTF-8">0 h0 u# h; [" S$ K* u
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
, q6 n0 J6 h0 t( G8 i# d - <title>WebSocket</title>& p% C# J% Q7 s
- </head>
1 s, [3 h, k( }0 O3 {1 Y - <body>( g/ h7 v6 K5 v3 m
- </body>
: j C9 `$ F& H/ ~- q$ |: m - <script>' {) w% Z# @% H8 c5 o, z& V
- var socket;; K! I" }/ c7 ^- ?2 y- I* o
- if (window.WebSocket) {
; `" z0 C9 s! [4 g% U" i - socket = new WebSocket("ws://localhost:8080/myapp");
; b6 |2 _$ a( _! {5 P$ m - socket.onmessage = function(event) {7 _# d2 z- V, l1 d! U
- alert("Received data from websocket: " + event.data);, n: u5 s. N5 d: C
- }
1 f2 H! R* x- A0 T+ h ` - socket.onopen = function(event) {
5 a- ]- \! l% s# B0 ]0 ?9 S - alert("Web Socket opened!");
) ^# P4 a" I( K; J - };* D" i- C) S$ I( F7 A
- socket.onclose = function(event) {9 U; ?- D) D( y% K
- alert("Web Socket closed.");
/ Z4 b0 N2 n$ o, Q6 {, `2 X - };4 c. }: E- U, l: v& R
- } else {
1 v0 B8 W3 _" b, E. x - alert("Your browser does not support Websockets. (Use Chrome)");
9 Z2 m( y# L8 M - }
5 W! W6 T8 o& _$ \( ` ? - * K! B3 G# D# }) W
- function send(message) {) D4 K2 G% {4 u9 y* j2 S4 o
- if (!window.WebSocket) {" \0 j) w) j3 {* N8 Y: d! {% ~3 G
- return;3 F6 t. x0 n- G/ H: E/ Y; P
- }
4 p# q8 F* N: S- |- f) h - if (socket.readyState == WebSocket.OPEN) {& h ~: N/ w7 s, `4 \. f' [
- socket.send(message);: V2 A2 b! n. z
- } else {! f- b* F8 e: T u5 e) u9 _
- alert("The socket is not open.");* b2 A# @5 g- L; y' L9 [1 f
- }: r2 z# S" W( Z W& a
- }; S7 W" L3 T( |: t
- </script>
1 ]% W4 m# r# ~4 _9 v3 E5 W$ b - </html>
复制代码 0 `0 A% e' ^) Y5 ?' b
: ~, d0 l/ F |! q% F) h( q5 V- J1 Q; Y! |) G: I
|