如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接: - var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码 V; I( M4 g& `) p2 d4 y+ T5 ^; d
与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
- ]8 I2 n, J7 ^# M# i
) `2 q- I1 q' r/ V' U# u. M4 K5 |5 v0 @' u, x* E; z! L
该套接口对象有四个用来监听套接口事件的回调: - socket.onopen = function(){ //打开' w% a% D) V$ F' w5 {* {5 @( n
- }: z F" \( v. M, R
- 7 J) d. t8 ~) S n; {" G
- socket.onmessage = function(){
1 ]! g/ ]1 h% |' x2 C* {0 b - //在event.data消息数据1 o8 K8 @2 m4 R
- }
]& Q/ E! O u
1 `8 Z8 {) ?3 F5 G$ d9 {- v0 @- socket.onclose = function(){# [0 w: `6 |: H9 @. y' T
- //关闭WebSocket0 m! ]8 k' D7 G1 K) \
- }. F9 y; [' l8 V1 A# O. M
2 B* u/ e( Q6 [; z7 b- socket.onerror = function(){
: H1 f5 r: ^0 U# l- H9 ?* N2 w, O - //错误触发
8 r! e; b& I0 g" J/ m - }
复制代码 5 _$ \9 ]1 j! j8 y |: I+ h& }& w
8 D: a4 w& B$ H8 j1 G
通过套接口发送数据,调用socket.send: " q& i' A/ x1 h2 X5 J
4 P+ g3 j8 O' \ u
: G, I4 |9 k x: X* X代码附上: - <!DOCTYPE html><html>0 J) n0 _% o8 c- I# E4 n5 S% t3 `
- <head>
! Q+ K) k! {) F. Z ` - <meta charset="UTF-8">
, y7 ~( i' y. B8 @# k r/ u - <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">: |+ x. Y( t$ S' a8 I; A
- <title>WebSocket</title>
: G) h. U- s* l( x1 b - </head>, h& ?* B1 a, \! g
- <body>
: S1 a% ^* y, K4 }+ U# M - </body>
4 C/ j3 i6 l3 |5 k( ] - <script>: O, |" h# I2 {
- var socket;
" r% q. K4 p z: o' [! P - if (window.WebSocket) {
: |: D l" w- [( S; F - socket = new WebSocket("ws://localhost:8080/myapp");
# m k" Z9 a! p& @/ k4 W - socket.onmessage = function(event) {
7 Y5 f; S$ I J - alert("Received data from websocket: " + event.data);
' h/ O3 u+ ~! h8 l" m+ m# k8 n* x' h5 T) h - }- r: A- y8 }$ Y/ x
- socket.onopen = function(event) {+ E9 _- J9 d+ ^, s+ R- g
- alert("Web Socket opened!");
4 y! }5 L$ c% B3 H+ l - };
3 o' Q0 d; O* T! j) X - socket.onclose = function(event) {5 F/ e5 A! V0 C7 o
- alert("Web Socket closed.");
1 N4 M% D3 ?# {5 l - };
4 L) q# i2 `3 D, V( v - } else {; D: }/ r( _% B
- alert("Your browser does not support Websockets. (Use Chrome)");
6 z6 J) k7 [8 Q6 Y- u" A, S - }
6 g9 q$ F& J5 T& |: m9 O- b0 ]) `
0 H; x2 c, W% p. d- function send(message) {! N* Z9 g* I& O1 w+ N) O- t
- if (!window.WebSocket) {5 l3 Q o5 H! [: r3 t
- return;
+ O B' n7 W9 Q( a- v - }
4 F6 c/ `0 Y3 X! J8 {" N7 \& o) ~ - if (socket.readyState == WebSocket.OPEN) {
8 ]- z! t5 o" S- [& {) { - socket.send(message);5 s7 z& ^, U7 n: ]8 v& e3 w
- } else {
* ]3 D1 f5 q# D6 a1 a5 @/ T7 |$ O) w% N - alert("The socket is not open.");
8 {# e) q% M0 W7 r/ p - }/ o( y/ p9 m" X( z. f6 a8 L3 J5 R, P( o
- } l" c) T3 @, \- Q$ O% q- @
- </script>
; f# | y% Q5 L/ D( Q - </html>
复制代码
2 m- ~# g$ ?7 I4 B( b( t6 `+ v' ^7 f+ v. Y
# c- b' ^# ?4 R8 A# V: D |