PHP套接字编程问题


PHP socket programming problem

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

我根据这个过去的堆栈溢出问题开发了PHP套接字客户端

<?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客户端

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

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

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

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

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

来自PHP文档:

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.
$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);