1. 程式人生 > >js-webSocket

js-webSocket

<!DOCTYPE html>
<html>
<head>
<title>WebSocket/SockJS Echo Sample (Adapted from Tomcat's echosample)</title>
<style type="text/css">
#console_container {
	float: left;
	width: 400px
}

#console_container div {
	padding: 5px;
}

#console_container {
	float: left;
	margin-left: 15px;
	width: 400px;
}

#console {
	border: 1px solid #CCCCCC;
	border-right-color: #999999;
	border-bottom-color: #999999;
	height: 170px;
	overflow-y: scroll;
	padding: 5px;
	width: 100%;
}

#console p {
	padding: 0;
	margin: 0;
}
#message{
    width: 350px;
}
</style>

<!-- 相容所有瀏覽器  自行檢視在此不過多介紹-->
<script src="http://cdn.sockjs.org/sockjs-0.3.min.js"></script>

<script type="text/javascript">
        var ws = null;
        var url = null;
        var transports = [];
        
        // 操作忌用屬性
        function setConnected(connected) {
            document.getElementById('connect').disabled = connected;
            document.getElementById('close_connect').disabled = !connected;
            document.getElementById('requser_message').disabled = !connected;
        }
 
        // 連線服務
        function connect() {
        	alert("url:"+url);
            if (!url) {
                alert('Select whether to use W3C WebSocket or SockJS');
                return;
            }
            // 判斷瀏覽器是否支援 WebSocket 
            ws = (url.indexOf('sockjs') != -1) ? new SockJS(url, undefined, {protocols_whitelist: transports}) : new WebSocket(url);
            
            // 連線
            ws.onopen = function () {
                setConnected(true);
                renderLog('客戶端onopen: 嗨!連線打開了.');
            };
            // 接收服務端返回資料 呼叫render方法輸出模版頁面
            ws.onmessage = function (event) {
                try {
                    renderLog('服務端msg: ' + event.data);
                } catch (error) {
                    renderLog('服務端msg: error' + JSON.stringify(event.data));
                }
            };

            //關閉連線
            ws.onclose = function (event) {
                setConnected(false);
                renderLog('客戶端onclose: 哇!連線關閉了');
                renderLog(event);
            };
        }
        
        //關閉連線
        function closeConnect() {
            if (ws != null) {
                ws.close();
                ws = null;
            }
            setConnected(false);
        }

        // 客戶端 必須建立連線   TCP連線  
        function requserMessage() {
            if (ws != null) {
                var message = document.getElementById('message').value;
                renderLog('客戶端send: ' + message);
                ws.send(message);
            } else {
                alert('connection not established, please connect.');
            }
        }
 
        function selectUpdateUrl(urlPath) {
            if (urlPath.indexOf('sockjs') != -1) {
                url = urlPath;
                document.getElementById('sockJsTransportSelect').style.visibility = 'visible';
            }else {
              if (window.location.protocol == 'http:') { // 如果http
                  url = 'ws://' + window.location.host + urlPath;
              } else {
            	  //安全的WebSocket協議 如果https
                  url = 'wss://' + window.location.host + urlPath;
              }
              document.getElementById('sockJsTransportSelect').style.visibility = 'hidden';
            }
        }
        
        // 選擇 sockjs 連線方式
        function updateTransport(transport) {
          alert(transport);
          transports = (transport == 'all') ?  [] : [transport];
        }
        
        // 輸出服務端返回資訊
        function renderLog(message) {
            var renderLog = document.getElementById('render_log');
            var p = document.createElement('p');
            p.style.wordWrap = 'break-word';
            p.appendChild(document.createTextNode(message));
            renderLog.appendChild(p);
            while (renderLog.childNodes.length > 25) {
                renderLog.removeChild(renderLog.firstChild);
            }
            renderLog.scrollTop = renderLog.scrollHeight;
        }
    </script>
</head>
<body>
	<noscript>
		<h2 style="color: #ff0000">Seems your browser doesn't support
			Javascript! Websockets rely on Javascript being enabled. Please
			enable Javascript and reload this page!</h2>
	</noscript>
	<div>
		<div id="connect-container">
			<input id="radio1" type="radio" name="group1"
				onclick="selectUpdateUrl('/websocket');"> <label for="radio1">W3C WebSocket</label> <br> 
				<input id="radio2" type="radio" name="group1"
				onclick="selectUpdateUrl('/sockjs/webSocketServer');"> <label for="radio2">SockJS</label>
			<div id="sockJsTransportSelect" style="visibility: hidden;">
                <span>SockJS transport:</span> 
                <select onchange="updateTransport(this.value)">
					<option value="all">all</option>
					<option value="websocket">websocket</option>
					<option value="xhr-polling">xhr-polling</option>
					<option value="jsonp-polling">jsonp-polling</option>
					<option value="xhr-streaming">xhr-streaming</option>
					<option value="iframe-eventsource">iframe-eventsource</option>
					<option value="iframe-htmlfile">iframe-htmlfile</option>
				</select>
			</div>
			<div>
				<button id="connect" onclick="connect();">連線</button>
				<button id="close_connect" disabled="disabled" onclick="closeConnect();">斷開</button>
			</div>
			<div>
				<textarea id="message">Here is a message!</textarea>
			</div>
			<div>
				<button id="requser_message" onclick="requserMessage();" disabled="disabled">傳送訊息</button>
			</div>
		</div>
		<div id="console_container">
			<div id="render_log"></div>
		</div>
	</div>
</body>
</html>