结合PHP Webservice和C#Client

时间:2015-10-28 15:27:30

标签: c# php web-services callback

我有一个使用PHP webservices的C#/ Winforms应用程序。第一个PHP webservice uploadFile.php用于在mysql数据库上上传blob文件(例如,通过unix应用程序),另一个webservice,getFile.php(下面的代码),用于获取文件,如果文件可用于客户。

目前客户端每隔5秒调用一次webservice。显然,Apache无法处理所有连接并且速度很慢而且经常停机或超时。今天我在2分钟内计算了2000个连接,在25分钟内计算了10万个。其中99%的人没有返回文件。

因此,我希望webservice uploadFile在结果可用时通知客户端,而不是每隔5(或10或20或其他)秒调用webservice。我不熟悉SOAP / REST或任何其他类型的Web服务,并且出于实际原因(旧版本的应用程序仍在运行)我无法用REST替换当前的Web服务。以下是webservice getOK.php目前所做的事情:

 if(getJobsForUser($login, $serveur)){

    //data is BLOB content
    $query = "SELECT idjob,fileName,data FROM JobSpool WHERE idcompte=$idcompte LIMIT 1" ;  
    $stmt = $pdo->query($query);
    $res = $stmt->fetch(PDO::FETCH_BOTH);  
    $idjob = $res[0] ;
    $nomfic = $res[1] ;
    $data = $res[2] ;
    //send datas to client
    echo $nomfic."\n" ;
    echo $data ; 
 }

 function checkJobsforUser($login, $serveur){
    global $pdo, $idcompte;

    $query = "SELECT count(*),c.idcompte FROM Compte as c,Job as j WHERE c.login='$login' AND c.serveur = '$serveur' AND j.idcompte = c.idcompte" ;

    $stmt = $pdo->query($query);
    $results = $stmt->fetch(PDO::FETCH_BOTH);
    //print_r($results);
    $count = $results[0];
    $idcompte = $results[1];
    //echo "count : $count, idcompte : $idcompte <br/>";
    if($count > 0)
        return true;
    return false;

}

C#代码:

public String getMyFile(){
    String nomFicFinal = String.Empty;
    try
    {
        HttpWebRequest hwr;
        String request = "http://myWebServiceDomain.com/getFile.php?login=myLogin&otherId=myOtherId";
        hwr = (HttpWebRequest)HttpWebRequest.Create(request);

        using (HttpWebResponse hwrep = (HttpWebResponse)hwr.GetResponse())
        {
            //read datas 
            br = new BinaryReader(hwrep.GetResponseStream());
            Byte[] tmp = new Byte[256];
            int b = br.Read();
            while (b != -1)
            {
                if (b == 10) break;
                tmp[indNomFic++] = (Byte)b;
                b = br.Read();
            }

            //get filename
            nomFicFinal = System.Text.Encoding.ASCII.GetString(tmp, 0, indNomFic);

            //if parsed data == "0" nothing returned
            if (nomFicFinal.Length == 1 && (nomFicFinal.CompareTo("0") == 0 || nomFicFinal.CompareTo("1") == 0))
            {
                br.Close();
                nomFicFinal = "";
            }
            else //we parse the content of the request and we create the file with the name nomFicFinal in ApplicationData
            {
                nomFicFinal = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + @"\MyApp\" + nomFicFinal;
                bw = new BinaryWriter(File.Open(nomFicFinal, FileMode.Create));

                tmp = new Byte[1024];
                while ((tmp = br.ReadBytes(1024)) != null)
                {
                    if (tmp.Length == 0) break;
                    bw.Write(tmp);
                    bw.Flush();
                }
                br.Close();
                bw.Close();
            }
        }
    }catch(Exception ex){
        //do something
    }

    return nomFicFinal;

}

我一直在搜索&#34;回调PHP C#&#34;等,但我仍然不清楚目前该怎么做。

1 个答案:

答案 0 :(得分:0)

我一直这样做。不要轮询网络服务!

从 Winforms 调用 PHP 网络服务(对不起,我仍然停留在 VB 中):

Public Function callServer(ByVal strURL As String, ByVal strCallString As String, Optional ByVal intWaitTimeIncrease As Integer = 0) As String

        'USE:  strResult = callServer(My.Settings.sf_GetData, SQL_Composite)

        callServer = ""

            If strCallString <> "" Then

                debugLog(strURL & " -> " & strCallString)

                strCallString = System.Web.HttpUtility.UrlEncode(strCallString) 'IF WE DONT ENCODE THIS HERE THEN ? & AND MAYBE OTHER CHARACTERS GET REMOVED

                Dim wRequest As HttpWebRequest = HttpWebRequest.Create(New Uri(strURL)) ' & "?SQL=" & Uri.EscapeDataString(SQL_Composite)))

                With wRequest

                    ' .AllowWriteStreamBuffering = False

                    .CookieContainer = ClientSettings.wsCookies
                    .Timeout = My.Settings.WebserviceTimeout + 5000 + My.Settings.WebserviceTimeoutUserAdjustment + intWaitTimeIncrease
                    .Proxy = ClientSettings.myWebProxy
                    .KeepAlive = False
                    .ContentType = "application/x-www-form-urlencoded" '"text/plain"
                    .Method = WebRequestMethods.Http.Post

                    Dim bPostData As Byte() = Text.Encoding.UTF8.GetBytes("SQL=" & strCallString)

                    .ContentLength = bPostData.Length

                    Using dataStream = .GetRequestStream()
                        dataStream.Write(bPostData, 0, bPostData.Length)
                    End Using

                    Using httpWebResponse = TryCast(.GetResponse(), HttpWebResponse)

                        If httpWebResponse IsNot Nothing Then

                            Dim responseUri As String = httpWebResponse.ResponseUri.AbsoluteUri

                            .CookieContainer.Add(httpWebResponse.Cookies)

                            Using streamReader = New StreamReader(httpWebResponse.GetResponseStream())
                                callServer = streamReader.ReadToEnd()
                            End Using

                            If callServer.StartsWith(vbCrLf) Then callServer = replaceFirstFound(callServer, vbCrLf, "")
                            If callServer.StartsWith(vbLf) Then callServer = replaceFirstFound(callServer, vbLf, "")

                        End If
                    End Using

                End With
            End If

    End Function

PHP

function exchangeData($compositeSQL) {
    //HERE YOU WRITE YOUR DATABASE CALLS AND RETURN INFORMATION
    //THEN YOU JUST 'return (string) x;' AS A PRODUCT OF THE FUNCTION
}

if (!empty($_POST["SQL"])) {
    echo (string) exchangeData($_POST["SQL"]);
}