socket

Socket是应用层与TCP/IP协议族通信的中间软件抽象层,它是一组接口。在设计模式中,Socket其实就是一个门面模式,它把复杂的TCP/IP协议族隐藏在Socket接口后面,对用户来说,一组简单的接口就是全部,让Socket去组织数据,以符合指定的协议。

socket 服务器端

//socket 服务器端
/*
 +-------------------------------
 *    @创建socket server整个过程
 +-------------------------------
 *    @socket_create
 *    @socket_bind
 *    @socket_listen
 *    @socket_accept
 *    @socket_read
 *    @socket_write
 *    @socket_close
 +--------------------------------
 */
//设置不超时并打印所以错误
error_reporting(0);
set_time_limit(0);
//检测php是否支持socket
if (!extension_loaded('sockets')) {
    die('The sockets extension is not loaded.');
    //需要打开扩展:extension=php_sockets.dll
}
//server的地址和端口
$address = "127.0.0.1";
$port = "10000";
//创建socket链接
$mysock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP) or die("Could not create socket\n");
//绑定地址和端口号
socket_bind($mysock, $address, $port) or die("Could not bind tosocket\n");
//监听
socket_listen($mysock, 5) or die("Could not set up socket listener\n");;
echo "Server started, accepting connections...\n";
//Socket来处理通信。这里会阻塞等待
$client = socket_accept($mysock) or die("Could not accept incomingconnection\n");
//发到客户端
$msg ="congratulations! you success!\n";
socket_write($client, $msg, strlen($msg));
echo "send to client: $msg\n";
//接收客户端的消息
$buf = socket_read($client, 8192);
echo "recvice from client: $buf\n"; 
//关闭
echo "Closing sockets...";
socket_close($client);
socket_close($mysock);

socket 客户端

//socket 客户端
/*
 +-------------------------------
 *    @client链接socket过程
 +-------------------------------
 *    @socket_create
 *    @socket_connect
 *    @socket_write
 *    @socket_read
 *    @socket_close
 +--------------------------------
 */
//设置不超时并打印所以错误
error_reporting(0);
set_time_limit(0);
//地址和端口号
$address = "127.0.0.1";
$port = 10000;
//创建socket链接
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
if ($socket === false) {
    echo "socket_create() failed: reason: " . socket_strerror(socket_last_error()) . "\n";
    die;
} else {
    echo "socket successfully created.\n";
}
//连接到地址和端口号
echo "Attempting to connect to '$address' on port '$port'...\n";
$result = socket_connect($socket, $address, $port);
if ($result === false) {
    echo "socket_connect() failed.\nReason: ($result) " . socket_strerror(socket_last_error($socket)) . "\n";
    die;
} else {
    echo "successfully connected to $address.\n";
}
//发给 server
$msg ="hello,I'm client\n";
socket_write($socket, $msg, strlen($msg));
echo "send to server: $msg\n";
//接收 server的消息
$buf = socket_read($socket, 8192);
echo "recvice from server: $buf\n";
echo "Closing socket...";
socket_close($socket);

参考链接