1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889 |
- <!DOCTYPE HTML>
- <html>
- <head>
- <title>My WebSocket</title>
- </head>
- <body>
- Welcome<br/>
- <input id="text" type="text" /><button onclick="send()">Send</button> <button onclick="closeWebSocket()">Close</button>
- <div id="message">
- </div>
- </body>
- <script type="text/javascript">
-
- function freshpage(){
- //获取总高度
- var heigh = document.body.scrollHeight;
- window.scrollTo(0,heigh);
- }
-
-
- var websocket = null;
-
- // var ipAdress = getUrlParms("ipAdress");
- var fileName = getUrlParms("fileName");
- var host = getUrlParms("ipAdress");
- //判断当前浏览器是否支持WebSocket
- if('WebSocket' in window){
- websocket = new WebSocket("ws://" + host + ":7771/webSocket/"+fileName);
- // websocket = new WebSocket("ws://localhost:7771/webSocket/"+"入参");
- }
- else{
- alert('Not support websocket')
- }
- //连接发生错误的回调方法
- websocket.onerror = function(){
- setMessageInnerHTML("error");
- };
- //连接成功建立的回调方法
- websocket.onopen = function(event){
- setMessageInnerHTML("open");
- }
- //接收到消息的回调方法
- websocket.onmessage = function(event){
- setMessageInnerHTML(event.data);
- freshpage();
- }
- //连接关闭的回调方法
- websocket.onclose = function(){
- setMessageInnerHTML("close");
- }
- //监听窗口关闭事件,当窗口关闭时,主动去关闭websocket连接,防止连接还没断开就关闭窗口,server端会抛异常。
- window.onbeforeunload = function(){
- websocket.close();
- }
- //将消息显示在网页上
- function setMessageInnerHTML(innerHTML){
- document.getElementById('message').innerHTML += innerHTML + '<br/>';
- }
- //关闭连接
- function closeWebSocket(){
- websocket.close();
- }
- //发送消息
- function send(){
- var message = document.getElementById('text').value;
- websocket.send(message);
- }
-
- //获取地址栏参数,name:参数名称
- function getUrlParms(name){
- var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
- var r = window.location.search.substr(1).match(reg);
- if(r!=null)
- return unescape(r[2]);
- return null;
- }
-
- </script>
- </html>
|