Websocket和PHP Socket編程

本來是搜一些html5 websocket資料看的,結果被引去看了php的socket編程。下面是一些簡單的例子,在命令行運行php腳本就行

[命令行運行PHP]PHP中有一個php.exe文件,可以用命令執行PHP腳本。如:D:/php.exe -f F:/test.php ; 可以使用php.exe -h查看更多參數

 

server端:

client端:

 

再看websocket協議,是HTTP協議升級來的。看其消息頭:

 

 

所以server端需要解析一下,並返回握手的協議內容:

在網上找到解析的相關代碼 phpwebsocket - url:   http://code.google.com/p/phpwebsocket/

 

 

繼承類:可以自己按需寫,這裏我添加了幾行代碼,sendAll()等,很方便就改成了一個即時的網頁版聊天室。

 

 

 


 

客戶端代碼:


 

<html>

<head>

<title>WebSocket</title>

 

<style>

 html,body{font:normal 0.9em arial,helvetica;}

 #log {width:440px; height:200px; border:1px solid #7F9DB9; overflow:auto;}

 #msg {width:330px;}

</style>

 

<script>

var socket;

 

function init(){

  var host = "ws://localhost:12345/websocket/server.php";

  try{

    socket = new WebSocket(host);

    log('WebSocket - status '+socket.readyState);

    socket.onopen    = function(msg){ log("Welcome - status "+this.readyState); };

    socket.onmessage = function(msg){ log("Received: "+msg.data); };

    socket.onclose   = function(msg){ log("Disconnected - status "+this.readyState); };

  }

  catch(ex){ log(ex); }

  $("msg").focus();

}

 

function send(){

  var txt,msg;

  txt = $("msg");

  msg = txt.value;

  if(!msg){ alert("Message can not be empty"); return; }

  txt.value="";

  txt.focus();

  try{ socket.send(msg); log('Sent: '+msg); } catch(ex){ log(ex); }

}

function quit(){

  log("Goodbye!");

  socket.close();

  socket=null;

}

 

// Utilities

function $(id){ return document.getElementById(id); }

function log(msg){ $("log").innerHTML+="<br>"+msg; }

function onkey(event){ if(event.keyCode==13){ send(); } }

</script>

 

</head>

<body onload="init()">

 <h3>WebSocket v2.00</h3>

 <div id="log"></div>

 <input id="msg" type="textbox" onkeypress="onkey(event)"/>

 <button onclick="send()">Send</button>

 <button onclick="quit()">Quit</button>

 <div>Commands: hello, hi, name, age, date, time, thanks, bye</div>

</body>

</html>

 

 

PS:

*  這個websocket的類文件可能有一點問題,客戶端握手後應該接收的第一條信息都丟失了,沒細看代碼,以後再檢查吧。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章