簡體   English   中英

C#-PHP套接字連接

[英]C#-PHP socket connection

我在通過服務器上的php腳本控制的PC上編寫程序。 我目前正在使用php來回傳輸ftp文件,並使用c#讀取文件並基於文件中的數據執行命令。 但是,這不是理想的解決方案。

我想查看有關如何使用php將數據發送到ac#程序pver套接字的教程或示例。

我想發送的數據示例

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

誰能指出我正確的方向?

與其嘗試讓服務器端的PHP腳本將數據發送到C#程序(這會讓您頭疼),不如在PHP腳本上寫一些東西,在給定頁面請求的情況下,輸出當前排隊的內容,而不是嘗試指示? 然后,C#程序可以向頁面發出WebRequest並接收其指令。

例如:

== 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")));

您可以使用PHP的soap擴展來創建SOAP WebService,可以從C#輕松調用它。 這樣,您就可以輸入訪問權限,而不必創建自己的協議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM