结合PHP Web服务和C#客户端


Combine PHP Webservice and C# Client

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

目前,客户端每5秒钟调用一次Web服务。显然,Apache无法处理所有的连接,速度会变慢,经常停机或超时。今天,我统计了2分钟内2000个连接,25分钟内100000个连接。其中99%没有返回文件。

因此,我不希望每5秒(或10秒或20秒)调用一次Web服务,而是希望Web服务uploadFile在结果可用时通知客户端。我不熟悉SOAP/REST或任何其他类型的Web服务,由于实际原因(应用程序的旧版本仍在运行),我无法用REST取代当前的Web服务

 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;
}

我一直在用"回调PHP C#"等进行搜索,但目前我还不清楚该怎么做。

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

从Winforms调用PHP Web服务(很抱歉我仍然被困在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"]);
}