顯示廣告
隱藏 ✕
看板 Mesak
作者 mesak (Mesak)
標題 [js] WebSocket Jquery Edit
時間 2013年05月09日 Thu. PM 12:23:54

https://code.google.com/p/jquery-websocket/

<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>WebSocket Chat</title>
</head>
<body>
<h1>WebSocket Chat</h1>
<section id="content"></section>
<input id="message" type="text"/>
<script src="http://www.google.com/jsapi"></script>
<script>google.load("jquery", "1.6.2")</script>
<script src="http://jquery-json.googlecode.com/files/jquery.json-2.2.min.js"></script>
<script>
/*
 * jQuery Web Sockets Plugin v0.0.1
 * http://code.google.com/p/jquery-websocket/
 *
 * This document is licensed as free software under the terms of the
 * MIT License: http://www.opensource.org/licenses/mit-license.php
 *
 * Copyright (c) 2010 by shootaroo (Shotaro Tsubouchi).
 */
(function($){
$.extend({
	
websocketSettings: {
	
	
open: function(){},
	
	
close: function(){},
	
	
message: function(){},
	
	
options: {},
	
	
events: {}
	
},
	
websocket: function(url, s) {
	
	
var ws = WebSocket ? new WebSocket( url ) : {
	
	
	
send: function(m){ return false },
	
	
	
close: function(){}
	
	
};
	
	
$(ws)
	
	
	
.bind('open', $.websocketSettings.open)
	
	
	
.bind('close', $.websocketSettings.close)
	
	
	
.bind('message', $.websocketSettings.message)
	
	
	
.bind('message', function(e){
	
	
	
	
var m = $.evalJSON(e.originalEvent.data);
	
	
	
	
if( m.dataType.toLowerCase() =='json' ){m.data = $.parseJSON(m.data) }
	
	
	
	
else if( m.dataType.toLowerCase() =='html' ){ m.data = $(m.data) }
	
	
	
	
var h = $.websocketSettings.events[m.type];
	
	
	
	
if (h) h.call(this, m);
	
	
	
});
	
	
ws._settings = $.extend($.websocketSettings, s);
	
	
ws._send = ws.send;
	
	
ws.send = function(type, data) {
	
	
	
var m = {type: type};
	
	
	
m = $.extend(true, m, $.extend(true, {}, $.websocketSettings.options, m));
	
	
	
if (data) m['data'] = $.isPlainObject(data) ? $.toJSON(data) : data;
	
	
	
return this._send($.toJSON(m));
	
	
}
	
	
$(window).unload(function(){ ws.close(); ws = null });
	
	
return ws;
	
}
});
})(jQuery);
</script>
<script>
var ws = $.websocket("ws://echo.websocket.org", {
	
	
options : {dataType:"json"},
        events: {
            message: function(e) {
           
	
$('#content').append('<h1>'+ e.data.name +'</h1><p>' + e.data.message + '</p>') 
            }
        }
});
$('#message').change(function(){
  ws.send('message',{"name":"Mesak","message" : this.value} );
  this.value = '';
});
</script>
</body>
</html>

--
Mesak Blog
http://mesak.oow.me
--
※ 作者: mesak 時間: 2013-05-09 12:23:54
※ 編輯: mesak 時間: 2013-05-09 12:31:55
※ 看板: Mesak 文章推薦值: 0 目前人氣: 0 累積人氣: 157 
分享網址: 複製 已複製
r)回覆 e)編輯 d)刪除 M)收藏 ^x)轉錄 同主題: =)首篇 [)上篇 ])下篇