Page 1 of 1

Sending and Receiving Data from a Webserver

#1 aj32  Icon User is offline

  • D.I.C Addict
  • member icon

Reputation: 30
  • View blog
  • Posts: 577
  • Joined: 30-August 07

Post icon  Posted 08 July 2008 - 10:03 PM

Sending and receiving data from a webserver

In this tutorial, I am going to show you how to work with a file on a web server to achieve tasks such as registration, activation, etc.
Doing this is actually not as hard as it may sound, but this tutorial will, hopefully, give you a good understanding of how to do this.


Ok, let's get started, first, we want to set up our required namespaces, we will need the following:
using System.Net;
using System.IO;



System.Net will be used by WebRequest & WebResponse.
System.IO will be used by Streams, and Stream Readers


Next, let's set up our variables. These variables will contain information on how to work with the file on the web server:
            //The method we will use to send the data, this can be POST or GET.
            string requestmethod = "POST";

            //Here we will enter the data to send, just like if we where to go to a webpage and enter variables,
            // we would type: "www.somesite.com?var1=Hello&var2=Server!"!
            string postData = "var1=Hello&var2=Server!";

            //The Byte Array that will be used for writing the data to the stream.
            byte[] byteArray = Encoding.UTF8.GetBytes(postData);

            //The URL of the webpage to send the data to.
            string URL = "http://www.foxsoftonline.net/testing/tutorial/targetpage.php";

            //The type of content being send, this is almost always "application/x-www-form-urlencoded".
            string contenttype = "application/x-www-form-urlencoded";

            //What the server sends back:
            string responseFromServer = null;



Ok, now that we have our variables set up, let's create the component that will be handling the data transfers:
We will need a WebRequest item to send the data to the server, and, if we want to get data back, we need a WebResponce item.
Also, we will need a StreamReader and StreamWriter object to send and receive the data.

            //Here we will create the WebRequest object, and enter the URL as soon as it is created.
            WebRequest request = WebRequest.Create(URL);

            //We also need a Stream:
            Stream dataStream;

            //...And a webResponce,
            WebResponse response;

            //don't forget the streamreader either!
            StreamReader reader;



With that done, the only part left is to send and receive data:

            //We will need to set the method used to send the data.
            request.Method = requestmethod;
            
            //Then the contenttype:
            request.ContentType = contenttype;

            //content length
            request.ContentLength = byteArray.Length;

            //ok, now get the request from the webRequest object, and put it into our Stream:
            dataStream = request.GetRequestStream();

            // Write the data to the request stream.
            dataStream.Write(byteArray, 0, byteArray.Length);

            // Close the Stream object.
            dataStream.Close();



Ok, we just sent that information to the server, now let's get the response:

            //Get the responce
            response = request.GetResponse();

            // Get the stream containing content returned by the server.
            dataStream = response.GetResponseStream();

            //Open the responce stream:
            reader = new StreamReader(dataStream);

            //read the content into the responcefromserver string
            responseFromServer = reader.ReadToEnd();

            // Clean up the streams.
            reader.Close();
            dataStream.Close();
            response.Close();


            //Now, display the responce!
            Console.WriteLine(responseFromServer);

            //Done!




...and that's it! We have just sent and received data to and from a web page.

The next thing you have to do is create the file on the server, I prefer to use php, but it can be any server-side language that can handle POST and GET.

Remember, that, when programming the server-side file, use the right methods to get the data, e.g. (PHP)
//USING THE [POST] METHOD:
$variable1 = $_POST['var1'];
$variable2 = $_POST['var2'];

//USING THE [GET] METHOD:
$variable1 = $_GET['var1'];
$variable2 = $_GET['var2'];



For an example, the php file on my server is:
<?php

$variable1 = $_POST['var1'];
$variable2 = $_POST['var2'];

if(strtoupper($variable1) == strtoupper("hello") && strtoupper($variable2) == strtoupper("server!"))
	echo("Hello CSharp Program!");
else
	echo("What do you want?");

?>



That being an example, I use this method when setting up product activation systems, I have the php code connect to a MySQL database server and work with that to activate the product. You could use this method to collect statistics about a program (given the end-user knows that the program is doing this ;)) or as I use it, an activation system!

As an ending note: You may want to have your program Ping the server to make sure that is is ready, but remember that not all servers respond to ping requests!
To do this, you can set up a method like below:
        private bool isonline()
        {
            try
            {
                Ping pingSender = new Ping();
                PingReply reply = pingSender.Send("google.com");
                if (reply.Status == IPStatus.Success || reply.Status == IPStatus.IcmpError)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (PingException EX)
            {
                return false;
            }
        }


You will need to add "System.Net.NetworkInformation;" to the list of namespaces used!

(I will leave that php file up on my server for a while, for example purposes! ;))

That's the end of this tutorial, I hope it is useful,
-AJ :)

Is This A Good Question/Topic? 0
  • +

Page 1 of 1