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");
复制代码
$ q1 j3 o' l- m, f0 B与http://这一URL 前缀等价的WebSocket 前缀 是 ws:// ,安全 WebSocket 则有一个与http://等价的 wss:// 前缀。 / ~4 k0 M* v3 m+ e
" g$ `+ \1 o9 W
* E6 c$ ~% N9 T$ {/ N该套接口对象有四个用来监听套接口事件的回调:
- socket.onopen = function(){ //打开
2 ^ F {$ z2 U4 m) J - }: d# d; a8 ~# v9 M+ O& b- p% m
- : ]; B' x& `) z( ~8 f9 N* f
- socket.onmessage = function(){
8 J6 T Y$ b6 i. R! [( u) Y& @ - //在event.data消息数据
& f5 ]; z% |2 J5 a/ X% z - }. m8 e4 ?% B- Q% Q% }/ B' I. x
- * d9 \ ^3 E2 N" M: y$ z: v( D4 g
- socket.onclose = function(){
# Y) e" m# [' A0 }' | - //关闭WebSocket
* V7 h8 i* U8 b8 p8 _ - }
& ^$ W! v" }' {" ]7 K7 a4 h9 q - / X, w8 S1 g: Z \% f7 y& h
- socket.onerror = function(){0 r, x& |# l8 b5 j$ ?$ [3 Q
- //错误触发
% N4 p5 m3 n3 k% E) G - }
复制代码 ) F$ U- B/ h" u% P( s @
! u3 k4 [. O# P u0 G0 u通过套接口发送数据,调用socket.send:
; L) O1 D2 H5 N3 ~( j
7 r& ?, j/ h4 d2 h3 O5 T; N. N* q4 ?5 x2 U/ P7 F* H$ m
代码附上:
- <!DOCTYPE html><html>
( a$ b3 f% y$ m8 C+ r: U - <head>0 ]1 C9 I9 q! H" r. t
- <meta charset="UTF-8">
9 G8 h# `2 z8 K - <meta content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" name="viewport">0 o5 y8 @8 Z, }6 E$ H
- <title>WebSocket</title>
7 w! u% k# G; R1 T - </head>* G! K* y* u# R) W; H$ g
- <body>) N) c3 q% P g _$ w% H: w; z
- </body>; Y; B; u" s+ s7 M# k: V a
- <script>
7 T% c) T; \: }! Z0 { - var socket;
1 \0 U% z: i. l) H - if (window.WebSocket) {
; r& K2 p; z3 F: A% ], T - socket = new WebSocket("ws://localhost:8080/myapp");
! _, Y( B$ E i: a" m& U3 E! R* V - socket.onmessage = function(event) {
5 t2 Y9 d5 }! L; p+ W9 g - alert("Received data from websocket: " + event.data);
( ]) x8 R2 }! Q" O8 B S7 Y - }
4 B' z) r4 Y+ ^ - socket.onopen = function(event) {4 O0 b0 A5 K q% B
- alert("Web Socket opened!");
: x% u" R' ?$ |2 R1 I4 i - };
* v3 \" I" c( @" X$ {7 ] - socket.onclose = function(event) {
3 c5 d6 X/ x ^2 p3 M$ p - alert("Web Socket closed.");8 s, C, O& P* A1 o" v7 U* \
- };
2 F, P, Y1 E* ?" D - } else {( L* J% _# |6 X7 a4 l/ E
- alert("Your browser does not support Websockets. (Use Chrome)");& Z# x# }8 q7 e
- }; S4 X: T) Y9 p# ?% I0 E5 y
# C+ y3 c' Q) d1 z( i- function send(message) {
4 p: M2 N5 W( X - if (!window.WebSocket) {
) ^- W9 M/ F0 j. |" o - return;
. m7 g7 l: e! |* C3 |6 T1 P+ U3 t - }
3 c1 p t+ m1 v - if (socket.readyState == WebSocket.OPEN) {/ s8 V+ @$ N& W, j6 l, M
- socket.send(message);, r% A& `7 w# n, i# q
- } else {+ P7 U: C* y; I$ a9 v* h+ E3 T
- alert("The socket is not open.");
9 G* J0 c4 l7 J1 B, W2 A$ p - }
' s. Z% i# S# d - }
0 U0 y- y2 ], G2 q - </script>
+ b" X! |8 X8 ^/ o& d' H* q - </html>
复制代码
Z, J' f# L- R8 k0 z2 j9 @0 s. z" N5 B X7 h
# `! p) E, d' C9 ], z0 V; x n
欢迎光临 cncml手绘网 (http://cncml.com/) |
Powered by Discuz! X3.2 |