C#-PHP套接字连接

4

我正在编写一个程序,通过服务器上的php脚本来控制pc。目前,我正在使用php进行文件传输,并使用c#读取文件并基于文件中的数据执行命令。但这不是一个理想的解决方案。

我希望能够看到有关如何使用php通过sockets向c#程序发送数据的教程或示例。

我想要发送的数据示例:

1:control1
1:control2
1:control3
0:control4
0:control5

有人能给我指一条正确的道路吗?
2个回答

2

与其让您的服务器端PHP脚本向C#程序发送数据,这将带来很多麻烦,不如在PHP脚本上编写一些内容,以满足对页面的特定请求,并输出当前排队的指令。然后,C#程序可以只需对该页面进行Web请求并接收其指令。

例如:

== PHP脚本 ==

<?php
    //main execution.
    process_request();

    function process_request()
    {
        $header = "200 OK";
        if (!empty($_GET['q']) && validate_request())
        {
            switch ($_GET['q'])
            {
                case "get_instructions":
                    echo get_instructions();
                    break;
                case "something_else":
                    //do something else depending on what data the C# program requested.
                    break;
                default:
                    $header = "403 Forbidden"; //not a valid query.
                    break;
            }
        }
        else { $header = "403 Forbidden"; } //invalid request.
        header("HTTP/1.1 $header");
    }

    function validate_request()
    {
        //this is just a basic validation, open to you for how you want to validate the request, if at all.
        return $_SERVER["HTTP_USER_AGENT"] == "MyAppName/1.1 (Instruction Request)";
    }

    function get_instructions()
    {
                    //pseudo function, for example purposes only.
        return "1:control1\n1:control2\n1:control3\n0:control4\n0:control5";
    }
?>

现在需要从请求中获取数据:
== C#客户端代码 ==
private string QueryServer(string command, Uri serverpage)
{
    string qString = string.Empty;

    HttpWebRequest qRequest = (HttpWebRequest)HttpWebRequest.Create(serverpage.AbsoluteUri + "?q=" + command);
    qRequest.Method = "GET";
    qRequest.UserAgent = "MyAppName/1.1 (Instruction Request)";

    using (HttpWebResponse qResponse = (HttpWebResponse)qRequest.GetResponse())
        if (qResponse.StatusCode == HttpStatusCode.OK)
            using (System.IO.StreamReader qReader = new System.IO.StreamReader(qResponse.GetResponseStream()))
                qString = qReader.ReadToEnd().Trim(); ;

    return qString;
}

这是一个简单的模板,只有最基本的错误处理,希望它足以让你开始。

编辑:哎呀,忘记包含一个使用示例:

MessageBox.Show(QueryServer("get_instructions", new Uri("http://localhost/interop.php")));

0

你可以使用 PHP 的 SOAP 扩展 来创建一个 SOAP WebService,这样你就可以轻松地从 C# 中调用它。这样你就有了类型化的访问,而且不必创建自己的协议。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接