如何将php套接字脚本转换为C#代码?

时间:2013-08-23 11:33:31

标签: c# php tcp

我在linux上运行tcp服务器,虽然我可以运行php -f test.php 在这台服务器上,我需要从Windows客户端执行此操作并获取结果。 php客户端脚本如下所示:

$Host = "192.168.2.70"; 
$Port = 8189;

$Socket = socket_create(AF_INET, SOCK_STREAM, 0) or die ("Error \n ".socket_strerror());
$Result = socket_connect($Socket, $Host, $Port) or die ("Error \n ".socket_strerror(socket_last_error()));

$message = 'CMD1;1;5;0;F;20130426;'."\n";

socket_write($Socket, $message, strlen($message)) or die ("Error \n ".socket_strerror());
$Result = '';

while($buf = socket_read($Socket, 2048 )) {
$Result = $Result.$buf;
}   

socket_close($Socket);
$handle = fopen ('./test.xml', "w");  

fwrite($handle, $Result, strlen($Result));  
fclose($handle);  

?>

和C#客户端我喜欢这个:

IPAddress ipAddress = IPAddress.Parse("192.168.2.70");
IPEndPoint remoteEP = new IPEndPoint(ipAddress,8189);

Socket sender = new Socket(AddressFamily.InterNetwork, 
                SocketType.Stream, ProtocolType.Tcp );

            try {
                sender.Connect(remoteEP);
                Console.WriteLine("Socket connected to {0}",sender.RemoteEndPoint.ToString());
                byte[] msg = Encoding.ASCII.GetBytes("'CMD1;1;5;0;F;20130426;'.'\n';");
                int bytesSent = sender.Send(msg);

                // Receive the response from the remote device.
                int bytesRec = sender.Receive(bytes);
                Console.WriteLine("Echoed test = {0}",
                Encoding.ASCII.GetString(bytes,0,bytesRec));

不幸的是它已连接但返回未知的命令消息。 PHP脚本在本地工作正常但是Windows客户端的C#没有,任何提示?无法在linux中调试服务器代码。

谢谢

0 个答案:

没有答案