一、什么是套接字
源IP地址和目的IP地址以及源端口号和目的端口号的组合称为套接字。其用于标识客户端请求的服务器和服务。
二、php套接字实例
服务端代码:socket.php
<?php error_reporting(E_ALL); set_time_limit(0); $chr_13_10 = "\r\n"; //回车 换行 //ob_implicit_flush(); $address = ‘127.0.0.1‘; $port = 10005; //创建 套接字 if( ($sock = socket_create(AF_INET, SOCK_STREAM, SOL_TCP)) === false) { echo "socket_create() failed: ", socket_strerror(socket_last_error()), $chr_13_10; } //将 套接字 绑定到端口 if (socket_bind($sock, $address, $port) === false) { echo "socket_bind() failed: ", socket_strerror(socket_last_error($sock)), $chr_13_10; } //允许其它 套接字 进行连接 if (socket_listen($sock, 5) === false) { echo "socket_bind() failed: ", socket_strerror(socket_last_error($sock)), $chr_13_10; } do { //等待连接 if (($msgsock = socket_accept($sock)) === false) { echo "socket_accepty() failed: ", socket_strerror(socket_last_error($sock)), $chr_13_10; break; } //读取客户端的信息 echo ‘client message: ‘,$chr_13_10; $buffer = socket_read($msgsock, 8192); echo $buffer,$chr_13_10; //将读取到的信息,返回给客户端 if (false === socket_write($msgsock, $buffer, strlen($buffer))) { echo "socket_write() failed: ", socket_strerror(socket_last_error($sock)), $chr_13_10; } //关闭本次连接 socket_close($msgsock); } while(true); //关闭 套接字 socket_close($sock);
客户端代码:client.php
<?php $chr_13_10 = "\r\n"; //回车 换行 $service_port = 10005; $address = ‘127.0.0.1‘; //创建 套接字 $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if ($socket === false) { echo "socket_create() failed: ", socket_strerror(socket_last_error()), $chr_13_10; } else { echo "socket create OK", $chr_13_10; } //连接到其它 套接字 $result = socket_connect($socket, $address, $service_port); if($result === false) { echo "socket_connect() failed: ", socket_strerror(socket_last_error($socket)), $chr_13_10; } else { echo "socket connect OK", $chr_13_10; } $in = ""; if(isset($argv[1])) $in .= $argv[1]; //向已连接的 套接字 写入信息 socket_write($socket, $in, strlen($in)); echo "socket write OK", $chr_13_10; echo "Reading response-------------------------->start", $chr_13_10; $out = ""; //读取已连接的 套接字 发来的信息 while ($out = socket_read($socket, 8192)) { echo $out; } echo $chr_13_10, "Reading response-------------------------->end", $chr_13_10; socket_close($socket); echo "socket close OK",$chr_13_10;
三、代码演示结果
1、打开一个cmd去启动服务端
2、再打开一个cmd去启动客户端
3、查看服务端对应的cmd
四、《HTTP权威指南》中截取的两张图片
1、TCP客户端和服务器通过TCP套接字接口进行通信的流程
2、对TCP连接进行编程所需的常见套接字接口函数
时间: 2024-09-29 23:50:23