【问题标题】:PHP socket programming problemPHP套接字编程问题
【发布时间】:2011-06-17 15:52:52
【问题描述】:

我已经使用C#PHP 中的客户端开发了一个套接字服务器,它连接良好.. 我只需要将一些数据从客户端发送到服务器。

我按照这个Past Stackoverflow Question开发了PHP socket客户端

<?php
$host="127.0.0.1" ;
$port=9875;
$timeout=30;
$sk=fsockopen($host,$port,$errnum,$errstr,$timeout) ;
if (!is_resource($sk)) {
    exit("connection fail: ".$errnum." ".$errstr) ;
} else {

    echo "Connected";
    }
?>

最后我需要的是使用这个 PHP 客户端

向套接字服务器发送一个数据(字节数组)

【问题讨论】:

    标签: php sockets


    【解决方案1】:

    fwrite(),有关示例,另请参阅fsockopen() 的手册页。

    $bytesWritten = fwrite($sk, $string);
    

    如果你有一个字节数组,在写入之前将其转换为字符串:

    $string = imlode('', $byteArray);
    

    【讨论】:

      【解决方案2】:

      来自PHP Documentation

      fwrite($sk, 'A message sent to the server');
      

      或者使用数组:

      $array = array(4, '3', 'Foo');
      fwrite($sk, serialize($array)); //You'll have to deserialize it on C# side.
      

      【讨论】:

        【解决方案3】:
        $msg = "Your message here";
        
        fwrite($sk, $msg);
        // Only if you expect some response
        while (!feof($sk)) {
            echo fgets($sk, 128);
        }
        // Close the stream
        fclose($sk);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2022-10-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-03-27
          • 1970-01-01
          相关资源
          最近更新 更多