Websocket和PHP Socket编程

来源:互联网 发布:java中session的用法 编辑:程序博客网 时间:2024/05/20 21:46

本来是搜一些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的类文件可能有一点问题,客户端握手后应该接收的第一条信息都丢失了,没细看代码,以后再检查吧。

 

原创粉丝点击