cncml手绘网
标题: 浏览器使用WebSocket实时通讯 [打印本页]
作者: admin 时间: 2018-6-23 19:36
标题: 浏览器使用WebSocket实时通讯
如果你要有一个支持 WebSocket的服务器(Java、Php等),可以在浏览器中使用一个新的WebSocket服务协议,来打开一个链接:
- var socket = new WebSocket("ws://172.0.0.1:8080/SpringWebSocketPush/websck");
复制代码
: Y* s8 p/ E# v# _8 e- _0 j与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。
3 O: o d8 A. ~: T6 \. n( T) e! c+ f) b
8 E) N+ |, Z7 j A7 R" o该套接口对象有四个用来监听套接口事件的回调:
- socket.onopen = function(){ //打开
( K1 \5 l; B% u* g& _ - }
* J, z: z6 Q6 Z% ]) i& H# o; g - - q/ D+ f1 X+ t: i/ e7 V" g
- socket.onmessage = function(){
* h3 w+ e: m! d - //在event.data消息数据9 X8 E$ h7 C6 G p) ~) O% U
- }
3 V, H% \* G2 Y2 B3 T - - i) h, L6 w0 C0 c3 F2 w
- socket.onclose = function(){* z6 h6 Y. n# O ^, ?6 N
- //关闭WebSocket0 x3 L" \# J/ J
- }
/ ~' q8 V1 b! ]: [! {1 ~+ |' g# p
# P1 S& T" n7 t- socket.onerror = function(){
& ^ P0 y& I6 @ - //错误触发
- Q. E4 u' N! @ J2 E: S - }
复制代码
7 f7 }/ Y% H: l& h, M8 s$ U- n0 H' K3 r6 N# h; A
通过套接口发送数据,调用socket.send:
( }5 S$ g/ j' U5 }0 c$ d: M$ m, R
( e" ]$ u g* x) H( s" Y& k. L' R E+ l. z
代码附上:
- <!DOCTYPE html><html>9 D1 N7 @2 u9 k5 U: _- E
- <head>: e7 Q- }' @% L) l) Q- n
- <meta charset="UTF-8">6 U/ b! _; ] u+ V4 C8 p' D
- <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">
2 E6 t$ ~9 t' [1 T5 | - <title>WebSocket</title>
$ }! x% |0 p3 ?+ I6 z0 `: i - </head>% q9 ~( Y# B% o6 a. y- ]. O. N4 j
- <body>, z& E# a4 @, i1 R( U2 o, c7 v, i
- </body>$ i2 S% c9 g4 b0 {: w
- <script>6 P& y3 Q# C/ c5 D" E
- var socket;, Z) P7 _- }" X2 S3 x) g* @
- if (window.WebSocket) {8 N t: C+ e, h# S5 P! k; z
- socket = new WebSocket("ws://localhost:8080/myapp");
5 N- x2 Z+ Z6 c7 C& D' \, Q - socket.onmessage = function(event) {
6 P+ X3 T8 l5 C8 C3 J C - alert("Received data from websocket: " + event.data);/ I: ^" V! N; o5 C. o! [% Y
- }
1 Y' v) v! M* A& R5 u: j, u - socket.onopen = function(event) {
. U& x' a5 y+ B6 O - alert("Web Socket opened!");+ a4 b, _0 B" Z
- };4 J Y( [9 D* t$ G% `6 }5 n
- socket.onclose = function(event) {
7 N3 \1 p* X4 C% \$ ^/ f - alert("Web Socket closed.");
7 H) `$ p) p4 T1 p) t& T, _4 h6 { - };
1 D7 d3 Q' N T5 H/ R - } else {) `& X3 R2 O5 ^1 h) ?; v* b3 C
- alert("Your browser does not support Websockets. (Use Chrome)");; c8 l2 O, I4 `( a
- }
9 ?+ r1 f. ^8 }! G
. v8 R3 Q$ q) U& ^4 h, w3 X- function send(message) {6 z; O4 `2 I4 s! N- q! A
- if (!window.WebSocket) {
# }, m1 a5 j2 F; j - return;
) ]7 P; n; p7 Q' p9 l3 c& u8 I) H - }( N2 J' H1 ^, }# d n& o6 v8 a
- if (socket.readyState == WebSocket.OPEN) {
6 m, V `( G+ H! X9 q& F1 A - socket.send(message);
& a# u9 `/ n5 @, b5 g5 [4 m - } else {
" u# i! u! W5 y' l - alert("The socket is not open.");0 R; F! f* B. K( I1 r! Q
- }+ b+ f% l& S2 P5 m1 }
- }2 _$ x$ f6 k! O N
- </script>
% d3 {- K7 _* d6 L# Y$ X& I" B - </html>
复制代码 ; m4 {$ n3 U( Z/ K6 Y
" y2 ^6 x* b) S. k5 G( d: T( S+ ~, m8 g7 a: M
欢迎光临 cncml手绘网 (http://bbs.cncml.com/) |
Powered by Discuz! X3.2 |