PHP进行tcp连接
程序员文章站
2022-03-17 09:40:25
...
本篇文章给大家分享的内容是PHP进行tcp连接,有着一定的参考价值,有需要的朋友可以参考一下
原生PHP的写法。
$host = '服务端IP'; $port = 端口号; $timeout = 5; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (socket_connect($socket, $host, $port) === false) { // 创建连接 socket_close($socket); $message = 'create socket error'; throw new Exception($message, socket_last_error()); } if (socket_write($socket, $buffer) === false) { // 发包 socket_close($socket); $message = sprintf("write socket error:%s", socket_strerror(socket_last_error())); throw new Exception($message, socket_last_error()); } socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout); $rspBuffer = socket_read($socket, 65536); // 接收回包 socket_close($socket);
使用swoole的写法。
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);$ret = $client->connect('服务端IP', 端口号, 0.5, 0); // 创建连接if (!$ret) { throw new Exception('connect error', $client->errCode); } $client->send($buffer); // 发包$rspBuffer = $client->recv(); // 接收回包
转载地址
https://www.liudon.org/1324.html
原生PHP的写法。
$host = '服务端IP'; $port = 端口号; $timeout = 5; $socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); if (socket_connect($socket, $host, $port) === false) { // 创建连接 socket_close($socket); $message = 'create socket error'; throw new Exception($message, socket_last_error()); } if (socket_write($socket, $buffer) === false) { // 发包 socket_close($socket); $message = sprintf("write socket error:%s", socket_strerror(socket_last_error())); throw new Exception($message, socket_last_error()); } socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, $timeout); $rspBuffer = socket_read($socket, 65536); // 接收回包 socket_close($socket);
使用swoole的写法。
$client = new swoole_client(SWOOLE_SOCK_TCP, SWOOLE_SOCK_SYNC);$ret = $client->connect('服务端IP', 端口号, 0.5, 0); // 创建连接if (!$ret) { throw new Exception('connect error', $client->errCode); } $client->send($buffer); // 发包$rspBuffer = $client->recv(); // 接收回包
转载地址
https://www.liudon.org/1324.html
相关推荐:
以上就是PHP进行tcp连接的详细内容,更多请关注其它相关文章!