Welcome to Dream.In.Code
Click Here
Getting C# Help is Easy!

Join 118,310 C# Programmers for FREE! Ask your question and get quick answers from experts. There are 1,672 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!



Sending and Receiving Data from a Webserver

 
Reply to this topicStart new topic

> Sending and Receiving Data from a Webserver

aj32
Group Icon



post 8 Jul, 2008 - 10:03 PM
Post #1


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:
csharp

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:
csharp

//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.

csharp

//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:

csharp

//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:

csharp

//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)
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

<?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 wink2.gif) 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:
csharp

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! wink2.gif)

That's the end of this tutorial, I hope it is useful,
-AJ smile.gif
Go to the top of the page
+Quote Post


Register to Make This Ad Go Away!


Fast ReplyReply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 

Lo-Fi Version Time is now: 10/10/08 12:02PM

Live C# Help!

C# Tutorials

Reference Sheets

C# Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month