Web QQ 原理,ajax方式模擬socket編程

技術參考文檔:
http://www.javaeye.com/topic/28020
http://www.pushlets.com/
http://www.meebo.com/[成功案例]
更新請在搜索引擎裏查找”服務器推技術”關鍵字
之前有寫過一篇文章,是描述如何用輪詢的方式實現用ajax方式模擬socket編程的。輪詢有很多缺點。服務器的負載性能是最關鍵的問題。之後我有想過很多辦法來實現。自己實現過一個http長連接的方式做的系統。實現很複雜,我在這裏就說一下怎麼使用。具體的實現,這個軟件包是開源的,基於C#。


軟件包地址:(包括一個介紹和下載

http://sites.google.com/site/websocketwiki/
下載地址:

http://sites.google.com/site/websocketwiki/download
整個系統依賴於 JQuery 和 .NET 3.5 框架
包內有個實例程序,具體的DEMO用法參見上述的網站。
用法介紹
<script type=”text/javascript” src=”Js/jquery.js”></script>
<script type=”text/javascript” src=”Js/WebSocket.js”></script>

這兩個文件可以在包內找到,請保證Server.aspx的位置可以被訪問到。具體的位置可以到WebSocket.js文件裏去找
var socket = new WebSocket();
1.新建一個實例

socket.Connect(strUserID);
2.以一個ID的身份連接服務器
socket.onConnect=function(){
alert(‘Already Connected’);
}

一個模擬事件機制,如果連接成功,則執行這個function裏的內容
socket.onConnectError=function(error_msg){
//deal with the error message
}

出錯也是這樣的機制
3.接受消息
function onReveive(msg){
if(msg!=”){
alert(msg);       //deal with the messages received
}
}

onReceive 函數是獨立的,必須存在的。msg參數就是接受到的消息。具體的處理用戶自己實現,這裏簡單的判讀如果是非空洞話,輸出。
4,斷開連接
socket.Disconnect(strUserID);
socket.onDisconnect=function(){
alert(‘Exited!’);
}

基本和連接一樣,因爲服務器端無法感知用戶的狀態,所以建議在onunload事件裏手動添加disconnect
window.οnunlοad=function(){
strUserID=$(‘#txtUserID’).val()   //replace the code
socket.Disconnect(strUserID);
}

在onunload事件裏寫類似這樣的代碼,以保證系統的穩定
提供的方法:
Connect(strUserID);
Disconnect(strUserID);
ListenOn(strUserID);
CreateHapping(strUserID,strSubject);
Join(strUserID,strHappeningID);
Send(strUserID,strMsg,strHappeningID);
Exit(strUserID,strHappeningID);
SendTo(strUserID,strMsg,strSendTo);

the strUserID means the id of user
the strSubject means the happening subject
the strHappeningID means the happening ID
the strMsg means the message content
the strSendTo means the user id of the target user id

提供的事件
onConnect()
onConnectError(error_msg)
onDisconnect()
onDisconnectError(error_msg)
onCreate(data)
onCreateError()
onJoin()
onJoinError(error_msg)
onSend()
onSendError(error_msg)
onExit()
onExitError(error_msg)
onSendTo()
onSendToError()
Happening 的概念

Happening 就相當於一個頻道,用戶可以創建,參加或者退出。類似一個臨時的“羣”,以實現數據交換。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章