iT邦幫忙

DAY 21
9

HTML5試試看系列 第 21

[HTML5試試看-21] 溝通 - WebSocket

  • 分享至 

  • twitterImage
  •  

如果要跟伺服器做雙向溝通,就需要使用到WebSocket。與EventSource類似,WebSocket在瀏覽器端的使用是非常簡單的。
先來研究一下WebSocket的定義:

 [Constructor(in DOMString url, in optional DOMString protocol)]
 interface WebSocket {
   readonly attribute DOMString URL;
   // ready state
   const unsigned short CONNECTING = 0;
   const unsigned short OPEN = 1;
   const unsigned short CLOSED = 2;
   readonly attribute unsigned short readyState;
   readonly attribute unsigned long bufferedAmount;
   // networking
            attribute Function onopen;
            attribute Function onmessage;
            attribute Function onclose;
   boolean send(in DOMString data);
   void close();
 };
 WebSocket implements EventTarget;

跟EventSource比較起來,constructor多了一個參數來指定protocol,多了一個bufferedAmount屬性,另外還多了一個send()的方法來傳送資料,其他看起來都差不多,世界一片美好。

先來寫個簡單測試網頁:

<html lang="zh-TW">

<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<style>
	div {
		border: solid 2px #336699;
		margin: 10px;
		padding: 5px;
		border-radius: 5px;
		vertical-align: top;
		text-align: center;
		display: inline-block;
	}
	.container {
		background: #88BBFF;
		width: 520px;
	}
	.msg {
		background: #99CCFF;
		border: dotted 1px #4477AA;
		width: 480px;
		margin: 0px;
		text-align: left;
		font-size: 12px;
	}
</style>
<script>
function init() {
	var form = document.getElementById('form1'),
	input = document.getElementById('input'),
	msg1 = document.getElementById('msg1'),
	ws = null;
	try {
		ws = new WebSocket('ws://localhost:8080');
	} catch(e) {
		if(window.console) console.log(e);
	}
	ws.addEventListener('message', function(e) {
		var str = '';
		str += '<li>[' + (new Date()) + ']: ' + e.data + '</li>\n';
		msg1.innerHTML += str;
	}, false);
	form.onsubmit = function() {
		try {
			ws.send(input.value);
			input.value = "";
		} catch(e) {
			if(window.console) console.log(e);
		} finally {
			return false;
		}
	};
}
</script>


<div><div class="container"><form id="form1"><input type="text" size="30" id="input"></form></div><br>
<div class="container">Returned Messages.<div id="msg1" class="msg"></div></div></div>


<script>
init();
</script>

網頁端只要這樣應該就ok了。然後來看看伺服器端...靠

The Websocket Protocol draft 76

這是一個IETF的規格草案,也就是將來會成為RFC...有五十五頁,而且目前的版本在今年(2010)十一月七日過期,下一個版本已經在十月十七日提出,而且會在明年(2011)四月二十日過期(頁數增加到六十頁)。

這樣...只好把伺服器部份放到明天了。

參賽文章


上一篇
[HTML5試試看-20] 溝通 - server sent event
下一篇
[HTML5試試看-22] 溝通 - WebSocket Protocol
系列文
HTML5試試看30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言