网络上的两个程序通过一个双向的通信连接实现数据的交换,这个连接的一端称为一个socket。
PHP有强大的Socket操作能力,它的处理方式更接近于C,但是没有C的繁琐。可以看作是对C操作的Socket的一个封装。
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
开启一个socket监听示例程序:<?php//设置一些基本的变量$host="192.168.1.99";$port=1234;//设置超时时间set_time_limit(0);//创建一个Socket$socket=socket_create(AF_INET,SOCK_STREAM,0)ordie("Couldnotcreatesocket
");//绑定Socket到端口$result=socket_bind($socket,$host,$port)ordie("Couldnotbindtosocket
");//开始监听链接$result=socket_listen($socket,3)ordie("Couldnotsetupsocketlistener
");//acceptincomingconnections//另一个Socket来处理通信$spawn=socket_accept($socket)ordie("Couldnotacceptincomingconnection
");//获得客户端的输入$input=socket_read($spawn,1024)ordie("Couldnotreadinput
");//清空输入字符串$input=trim($input);//处理客户端输入并返回结果$output=strrev($input)."
";socket_write($spawn,$output,strlen($output))ordie("Couldnotwriteoutput
");//关闭socketssocket_close($spawn);socket_close($socket); |