【问题标题】:Send/Receive data using Sockets functions使用 Sockets 函数发送/接收数据
【发布时间】:2013-02-15 07:05:51
【问题描述】:

如何将数据从 PHP 页面发送到 TCP 端口?

<?php 
// parameters to connect to server
$ip = "192.168.1.3";
$port = "59995";
$data = "Hello";
$output = "";

// Create a TCP Stream Socket
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);

// Connect to the server.
$result = socket_connect($socket, $ip, $port);

// Write to socket!
socket_write($socket, $data, strlen($data));

// Read from server
do 
{
  $line =@socket_read($socket,2048);
  echo $line. "\n";
} 
while ($data != "0");

// Close and return.
socket_close($socket);
?>

我正在使用它,但我无法接收任何数据!另外,你知道我如何为此设置超时吗?

有什么问题?

【问题讨论】:

标签: php sockets port


【解决方案1】:

您的程序有效。如果它没有收到数据,可能是服务器的问题。当然,你想要

while ($line);

而不是

while ($data != "0");

在服务器关闭连接时让它停止。 对于接收超时(例如 7 秒),您可以使用

socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array("sec"=>7, "usec"=>0));

【讨论】:

    猜你喜欢
    • 2011-08-06
    • 2014-07-08
    • 2016-09-11
    • 2015-11-12
    • 2019-07-10
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 2020-02-09
    相关资源
    最近更新 更多