Socket Programming- TCP client

2 01 2008

This a very basic tutorial for TCP server-client.

The code against tcp-server , the Clients Code

#define SRVR_PORT 4030 // The Server’s Port which Client is going to Connect.

#define MAXBUFLEN 100// Buffer Size for Sending/Receiving

int main(int argc, char *argv[])
{

//Declaration
int sockfd;
struct sockaddr_in their_addr; // connector’s address information
struct hostent *he;
int numbytes;
char buf[MAXBUFLEN];

//The Code to Take Server’s Address at Commandline

//You can remove this and assign your server’s Address you want

if (argc != 2)
{
fprintf(stderr,”usage: ./client 127.0.0.1\n”);
exit(1);
}

if ((he=gethostbyname(argv[1])) == NULL) { // get the host info
perror(“gethostbyname”);
exit(1);
}

//Creating the Socket(The Door for Communication)

if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
perror(“socket”);
exit(1);
}

//Setting the Attributes for Server Address


their_addr.sin_family = AF_INET; // host byte order
their_addr.sin_port = htons(SRVR_PORT); // short, network byte order
their_addr.sin_addr.s_addr = inet_addr(“127.0.0.1″);//*((struct in_addr *)he->h_addr);
memset(&(their_addr.sin_zero),”,8); // zero the rest

int addrlen = sizeof(struct sockaddr);

//Connecting to The Server

//connect return the status for successful connection or failure

int status;
status = connect(sockfd,(struct sockaddr*)&their_addr,addrlen);

while(1)
{

//Taking Input msg from Console

//Remove this if you not want from console Then use strcpy to fill the buffer

cout << “Enter ur message: “;
gets(buf);

//The buffer conatain the message you want to send to server

// The send method sends to the sevrer , just give socket id , buffer , and buffer size to send

// and off course give error on failure

if ( (numbytes=send(sockfd, buf, strlen(buf) , 0)) == -1)
{
perror(“send”);
exit(1);
}

// To Nullify or Empty to the buffer use memset method

memset(buf,”,MAXBUFLEN-1);

// The recv method is used for tcp recive , just sock id, buffer in which recv and length

// method return non-positive value for error

if ((numbytes=recv((int)sockfd,buf, MAXBUFLEN-1, 0)) == -1)
{
perror(“recv”);
exit(1);
}

cout << “from server>” << buf << endl;
memset(buf,”,MAXBUFLEN-1);

}

printf(“sent %d bytes to %s\n”, numbytes,inet_ntoa(their_addr.sin_addr));

close(sockfd); // It’s good to close the socket(the door) after Communication

return 0;

}

Let me know if you not uderstand any thing. I will upload the complete source code.





Array,C#

11 12 2007

Arrays

Just as enumerations group constants together, so arrays can be thought of as grouping variables together. There’s a lot of support for arrays built into C#, and we’ll take a look at it in Chapter 6. As you know, arrays store data values by index. In C#, arrays are reference types, so you can create a new array with the new operator. You declare an array as type[], where type is the data type of each element. For example, here’s how to declare an array of five integer elements:

int[] array1 = new int[5];

These elements can be addressed with index values 0 to 4, as array1[0], array1[1], up to array1[4]. You can see this at work in Listing 1.5, where we’ve created a C# array, placed data in one of its elements, and displayed that data.

FOR C++ PROGRAMMERS

In C#, you need to declare arrays as type[] name; the optional C++-style declaration type name[]; isn’t available in C#.

Listing 1.5 Using an Array (ch01_05.cs)
class ch01_05
{
  static void Main()
  {
    int[] array1 = new int[5];
    array1[0] = 1;
    System.Console.WriteLine("The first element holds {0}.", array1[0]);
  }
}

You can also initialize each element in an array when you declare the array by assigning it a list of values

int[] array1 = {1, 2, 3, 4, 5};
array1[0] = 1;
System.Console.WriteLine("The first element holds {0}.", array1[0]);

One common use of arrays is for reading arguments typed on the command line when your code is invoked. If you declare an array of type string[] in the parentheses following the Main method, C# will fill that array with any command-line arguments. You can see an example in Listing 1.6, set up to take exactly four command-line arguments (any more or any less will cause an error in this example).

Listing 1.6 Using an Array (ch01_06.cs)
class ch01_06
{
  static void Main(string[] args)
  {
    System.Console.WriteLine("You entered: {0} {1} {2} {3}.",
      args[0], args[1], args[2], args[3]);
  }
}

Here’s what you see when you run this example and type the command-line arguments "Now is the time" into this code:

C:\>ch01_06 Now is the time
You entered: Now is the time.

BOOK  : Microsoft® Visual C#® .NET 2003 Kick Start

Microsoft® Visual C#® .NET 2003 Kick Start




Enumerations, c#

11 12 2007

Enumerations

Enumerations are an alternative to constants, and provide a way of grouping constants together logically. For example, say you’re using a lot of constants like this:

const int Sunday = 1;
const int Monday = 2;
const int Tuesday = 3;
const int Wednesday = 4;
const int Thursday = 5;
const int Friday = 6;
const int Saturday = 7;
System.Console.WriteLine("Sunday is day {0}", Sunday);

This code will give you this output:

Sunday is day 1

However, all the constants you’ve created can be put into an enumeration, which groups them together logically. Here’s how you create an enumeration, using the enum statement:

[attributes] [modifiers] enum identifier [:base-type] {enumerator-list};

Here are the parts of this statement:

  • attributes (optional)— Holds optional declarative meta-information.

  • modifiers (optional)— Optional modifiers that include the new modifier and one of the four access modifiers like public and private.

  • identifier The enumeration name.

  • base-type (Optional)— The underlying type that specifies the storage allocated for each enumerator. It can be any of the integral types except char. The default is int.

  • enumerator-list The enumerators’ identifiers separated by commas, optionally including a value assignment.

Enumerations act like groups of constants, which can be any of the built-in signed or unsigned integer types (such as int, Byte, or UInt64, but not char). You can see an example in ch01_04.cs, in Listing 1.4, which declares an enumeration named Days (unless you declare a type like this, enum Days :uint {...}, the underlying type used for the constant in enumerations is int). (Note that the values in that example ascend smoothly from 1–7, but enumeration values can take any values consistent with their underlying type.)

Listing 1.4 Using an Enumeration (ch01_04.cs)
class ch01_04
{
  enum Days
  {
    Sunday = 1,
    Monday = 2,
    Tuesday = 3,
    Wednesday = 4,
    Thursday = 5,
    Friday = 6,
    Saturday = 7,
  }

  static void Main()
  {
    System.Console.WriteLine("Sunday is day {0}", (int) Days.Sunday);
  }
}

The code in Listing 1.4 will also give you this output:

Sunday is day 1

Note that we specify the type for constants in the Days enumeration by prefacing them with the cast (int), which casts the member of the enumeration to its underlying type:

System.Console.WriteLine("Sunday is day {0}", (int) Days.Sunday);

We’ll cover casts in a few pages; the upshot is that if you omit that cast, the value of Days.Sunday would be its symbolic name, “Sunday”, the value of Days.Monday would be “Monday” and so on, not the integers 1, 2, and so on. That’s because in C#, enumerations are formal data types, which means you have to convert them to their underlying types if you want to access the values each enumeration member stands for.

From : Microsoft® Visual C#® .NET 2003 Kick Start





Magic of C# with respect to C++

11 12 2007

A good comparison of C# and C++  Language, By Eric Gunnerson, specially for those who are in Transformation for c/c++ to C#.

Eric is a Microsoft Employee and written some books such as A Programmer’s Introduction to C#.

The comparison goes by

  • Automatic memory management
  • Exceptions
  • Coherent libraries
  • Compilation Model
  • Tools
  • Code == Component
  • Language Complexity
  • The alternate view
  • Absolute control over your memory
  • Quick boot time
  • Smaller memory footprint
  • Fewer install dependencies
To SEE : http://blogs.msdn.com/ericgu/archive/2005/01/26/360879.aspx




Heap Sort Algorithm

11 12 2007

The heap sort does not require massive recursion or multiple arrays to work. This makes it an attractive option for very large data sets of millions of items.

The heap sort works as it name suggests – it begins by building a heap out of the data set, and then removing the largest item and placing it at the end of the sorted array. After removing the largest item, it reconstructs the heap and removes the largest remaining item and places it in the next open position from the end of the sorted array. This is repeated until there are no items left in the heap and the sorted array is full. Elementary implementations require two arrays – one to hold the heap and the other to hold the sorted elements.

To do an in-place sort and save the space the second array would require, the algorithm below “cheats” by using the same array to store both the heap and the sorted array. Whenever an item is removed from the heap, it frees up a space at the end of the array that the removed item can be placed in.

Heap Sort Routine

// array of integers to hold values
private int[] a = new int[100];

// number of elements in array
private int x;

// Heap Sort Algorithm
public void sortArray()
{
int i;
int temp;

for( i = (x/2)-1; i >= 0; i– )
{
siftDown( i, x );
}

for( i = x-1; i >= 1; i– )
{
temp = a[0];
a[0] = a[i];
a[i] = temp;
siftDown( 0, i-1 );
}
}

public void siftDown( int root, int bottom )
{
bool done = false;
int maxChild;
int temp;

while( (root*2 <= bottom) && (!done) )
{
if( root*2 == bottom )
maxChild = root * 2;
else if( a[root * 2] > a[root * 2 + 1] )
maxChild = root * 2;
else
maxChild = root * 2 + 1;

if( a[root] < a[maxChild] )
{
temp = a[root];
a[root] = a[maxChild];
a[maxChild] = temp;
root = maxChild;
}
else
{
done = true;
}
}
}

You can download the full code here, or the compiled code here.

further : http://www.publicjoe.f9.co.uk/





Selection Sort Algorithm C#

11 12 2007

The selection sort works by selecting the smallest unsorted item remaining in the list, and then swapping it with the item in the next position to be filled.

This is a performance improvement over the bubble sort, but the insertion sort is over twice as fast as the bubble sort and is just as easy to implement as the selection sort. In short, there really isn’t any reason to use the selection sort – use the insertion sort instead.

If you really want to use the selection sort for some reason, try to avoid sorting lists of more than a 1000 items with it or repetitively sorting lists of more than a couple hundred items.

Selection Sort Routine

// array of integers to hold values
private int[] a = new int[100];
// number of elements in array
private int x;

// Selection Sort Algorithm
public void sortArray()
{
int i, j;
int min, temp;

for( i = 0; i < x-1; i++ )
{
min = i;

for( j = i+1; j < x; j++ )
{
if( a[j] < a[min] )
{
min = j;
}
}

temp = a[i];
a[i] = a[min];
a[min] = temp;
}
}

You can download the full code here, or the compiled code here.

for further : go Here