1

[Answer]
The answer to my original post is marked (Kimmax's first post).
It turns out that I should have initially mentioned that this is running (for now) out of an Android emulator. I found out that the IP for connecting to a localhost through the emulator is "10.0.2.2". Having the port number doesn't seem to matter. Running the same code as bare-bones as possible returned the page text. That meant it was something in Android causing the issue. Hopefully this post will save others some time.

[Original]
I'm new to web/socket programming, so I don't know any common practices specific to it. I'm trying to send a fairly short string (maybe 32 characters max) to a php page (I control). That php page would then process that string as needed and send a response string back to the sender. This is the extent of the connection (time-wise) needed between client and server. I've scoured the web looking for a simple answer, but can't seem to find any I'm hoping someone here can help.

For example: let's say the initial request string is a name ("Bob"). The php page on the server receives that and through handling figures out that the proper return string/value (say, an age "31"). This string/value is then sent to and received by the origional requestor to be handled as needed.

I'm only looking for the most short and basic of answers. Right now the server is a wamp localhost with the php page I'm testing with in a subdirectory (localhost/subdir/test.php).

[Edit]
Code example after using Kimmax's example:
C#

public String DownloadFrom(String url)
{
    string str = "";  // For debugging only
    try
    {
        using(WebClient client = new WebClient())
        {
            str = client.DownloadString(new Uri(url));
            return str; 
        }
        catch(WebException e) {
            Log.Error ("Error while receiving data from server:", e.Message);
            return null;
        }
    }
}

Value being passed to this function is "http://localhost/php/test.php?name=Bob"

test.php:

<?php
include 'logging.php';

if(isset($_GET['name']) && !empty($_GET['name']))
{
    $data = $_GET['name'];
    logg("test.php: name received: " . $data);

    $download = "Test string.";

    logg("test.php: setting data for download: " . $download);

    print $download;
}
?>

The logging.php file provides the logg function which just appends the given string to a file elsewhere. The test.php page will output $download when you enter that address into a browser, but nothing is returned through the given C# code. Even the log file doesn't get written to through the C# code. After some debugging I noticed that the WebException was thrown. The exception message is "Error: ConnectFailure (Connection refused)".

Full exception stacktrace:

e   {System.Net.WebException: Error: ConnectFailure (Connection refused) ---> System.Net.Sockets.SocketException: Connection refused
  at System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP) [0x00000] in <filename unknown>:0 
  at System.Net.WebConnection.Connect (System.Net.HttpWebRequest request) [0x00000] in <filename unknown>:0 
  --- End of inner exception stack trace ---
  at System.Net.HttpWebRequest.EndGetResponse (IAsyncResult asyncResult) [0x00000] in <filename unknown>:0 
  at System.Net.HttpWebRequest.GetResponse () [0x00000] in <filename unknown>:0 
  at System.Net.WebClient.GetWebResponse (System.Net.WebRequest request) [0x00000] in <filename unknown>:0 
  at System.Net.WebClient.ReadAll (System.Net.WebRequest request, System.Object userToken) [0x00000] in <filename unknown>:0 
  at System.Net.WebClient.DownloadDataCore (System.Uri address, System.Object userToken) [0x00000] in <filename unknown>:0 }    System.Net.WebException

I was able to get text returned during a telnet localhost 80 GET, so it seems that the connection should be viable. Am I missing some permissions somewhere?

[Edit]
Nothing has changed after completely disabling the firewall and setting up port forwarding on my router - I'm not ruling anything out at this point. I've also tried using the local IP address (127.0.0.1) instead of localhost. Snippet from access.log:

...
192.168.1.1 - - [01/Jul/2014:11:48:18 -0500] "GET /HNAP1/ HTTP/1.1" 404 292
192.168.1.1 - - [01/Jul/2014:11:48:18 -0500] "POST /JNAP/ HTTP/1.1" 404 291
192.168.1.1 - - [01/Jul/2014:11:48:18 -0500] "GET / HTTP/1.1" 200 4821
127.0.0.1 - - [01/Jul/2014:11:50:06 -0500] "GET /php/test.php?s=Bob HTTP/1.1" 200 16
127.0.0.1 - - [01/Jul/2014:11:50:11 -0500] "GET /php/test.php?s=Foo HTTP/1.1" 200 16
127.0.0.1 - - [01/Jul/2014:11:50:15 -0500] "GET /php/test.php?s=Bar HTTP/1.1" 200 16

The last three lines are from me typing in the link into a browser (Chrome). I believe that the first three are from the C# code - oddly, I think that they were written after I stopped debugging.

Nothing seems to be dumping in the apache_error.log file for these connect attempts.
There must be some minuscule detail I'm overlooking...

1
  • Use WebClient,HttpClient or HttpWebRequest. Commented Jun 29, 2014 at 16:42

1 Answer 1

4

If you just want to receive the response from the website I would recommend using the WebClient class with its .DowloadString() method.

Example

whatsmyname.php

<?php
    $name = $_GET['name'];
    echo "Your name is $name."
?>

whatsmyname.cs

private void btnSayMyName_Click(object sender, EventArgs e)
{
    string response = SendRequest("http://localhost/whatsmyname.php?name=" + txtMyName.Text);

    if(response != null)
    {
        MessageBox.Show(response, "Hey there!", MessageBoxButtons.OK, MessageBoxIcon.Information);
    }
}

private string SendRequest(string url)
{
    try
    {
        using (WebClient client = new WebClient())
        {
            return client.DownloadString(new Uri(url));
        }
    }
    catch(WebException ex)
    {
        MessageBox.Show("Error while receiving data from the server:\n" + ex.Message, "Something broke.. :(", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
        return null;
    }
}

Please read this to understand what's going on, it's pretty basic.

Sign up to request clarification or add additional context in comments.

7 Comments

That example sounds great! How do I send a message back from the php page or set the string for download?
As you cann see in the first code block there is a echo part and everything behind it in the quotes will be outputed anf therefore downloaded. So you will have to change this part. Please consider acepting the answer if it helped you :)
Wow, that's simple! Sadly, as I've been testing out that code, nothing is being downloaded. I was able to get some text from trying Google's page, though. Therefore I think it must be how the localhost uri is formatted. I have the test page logging some info, but, nothing is logged when the DownloadString is called. Even specifying the port number (Wamp's default is 80) doesn't work. What am I missing?
Okay as you can read from the Exception the connection gets refused, therefore your request doesn't get executed, so there won't be any logging. We need to find the reason for the disconnect is the application blocked in a Firewall? Is the path right (We could say yes, because you would propertly get another Exception)? Have you checked the access.log and error.log of your webserver? The code looks okay for me, so there is another problem.
@CheeseMo Okay so we can see that no request are going from your application to the webserver. What I'm worrying about is the HNAP1 404 in your request. The HNAP request is an attempt to take advantage of an old d-link security flaw and as it comes from a local IP please scan it for any malware etc. To your main problem: Could you try to use the download code in a very basic application (For example in a console application) and see if it fails too?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.