Click here to Skip to main content
Click here to Skip to main content

Multi Threaded Client Server

, 28 Dec 2006
Rate this:
Please Sign up or sign in to vote.
how a server can send data to any number of clients simultaneously is described here with a simple server program and a client program

Introduction

This Article is for describing how Server Clients are connected in Internet(from programming point of view) and how a Server gives data to any number of Clients simultaneously.

For understanding this article first you have to know what is internet SOCKET? So lets start…

What is Socket

Among the various process of communications between two or more than two number of computers Socket is one of the most popular process now a days. It communicates between a client and a server.More precisely it communicates between a server program and a client program. Socket may be called a communication end-point unique to a machine.

Sockets are created by sockets application-programming interface (API). If you don’t know what is API (Application Programming Interface) read this tutorial after having some knowledge of Windows API.Wait for a moment...read the next para.  

Briefly it may be called that Windows API is a set of functions provided by Windows to help application developers. These functions are given in Windows DLL files. The Windows Operating System itself uses these API.For working with sockets Windows also provides some functions commonly known as SOCKET API.These API are independent of programming language you may use this API functions by any language like c,c++ etc. It’s enough for giving some concept on API. Lets go to our own ground SOCKET…

Sockets can also be used for communication between processes within the same computer.

Sockets are formed by the followings.

  • Protocol (TCP, UDP, raw IP)
  • Local IP address
  • Local port
  • Remote IP address
  • Remote port

Protocol: It is a set of rules, which is using globally for communication purposes.

Local IP address: It is the IP address of the local machine.

Local port: It is the local port number.

Remote IP address: It is the IP address of the other machine on which local machine is connected through Socket.

Remote Port: It is the port number of the other machine.

For working with sockets in Windows OS you have to initialize the Winsock. Strange what is it?

The Windows Sockets (abbreviated "Winsock" or "WinSock") specification defines a network-programming interface for Microsoft Windows.

There are many versions of Winsock is available now like Winsock 1.1,Winsock 2.0,

Winsock 2.1 etc.

For using Winsock API you have to link to the libraries mpr.lib and wsock32.lib. To do this in Visual Studio creates a new project then under the "Projects" menu choose "Settings". In the top left of the dialog box there is a drop down list box "Settings For" change it to "All Configurations". In the tab control on the right of the dialog box select the "Link" tab. In the middle of the tab there is an edit box "Object/Library Modules:" add the name of the libraries you want to link to, be sure all the libraries in the list are separated by spaces. That being done you can now begin to program.

Initializing Winsock API is the 1st step for using Winsock in your application This is done by calling a function named WSAStartup(). This function takes two parameters a version number in a WORD value and a WSADATA structure, it returns an integer the return will be 0 if initialization is successful else it will be a non zero number.

Here is an example of the initialization process:

WSADATA WsaDat;

if (WSAStartup(MAKEWORD(1, 1), &WsaDat) != 0)
{
printf("WSA Initialization failed.");
}

For the version number macro MAKEWORD () is used here. The value in the parameter 1.1 is the version number used here it is possible to change the version number like 1.0, 2.0 etc. But remember that version 2.0 is not available in Win 95 without being specifically installed it does exist in all later versions of Windows.

How the Server works

After initializing the Winsock you may create a socket-by-socket function (SOCKET API). Sockets are of two types stream sockets and datagram sockets. All sockets are of type SOCKET.SOCKET is a structure and you create them with the socket () function. The socket () function takes three parameters. The first is the type of connection you would like to use, for this use AF_INET this designates you want to use an Internet style connection (or in other words use TCP/IP). The second parameter is the type of socket to use, for stream sockets use SOCK_STREAM, or for datagram sockets use SOCK_DGRAM. The thrid parameter is some value for the protocol from what I have read this value has very little meaning and is usually ignored so I always pass zero here.

The socket () function will return the socket or INVALID_SOCKET if it can't create the socket. Here is the code for creating sockets

SOCKET Server;

Server = socket (AF_INET, SOCK_STREAM, 0);

if (Server == INVALID_SOCKET)

{

printf("\n\n Socket creation failed!!!!STOP!!!");

exit(1);

}

else

{

printf("\n\n SOCKET IS CREATED SUCCESSFULLY...");

}

Here Server is a variable of type SOCKET.SOCKET is a structure.

Socket communication is based on the client server model. A client request a server for a connection to build the server must be ready in a listening mode for accepting in connection from client.

For accepting any connection with client the socket of the server must be bind the socket to a TCP/IP port. Bind function takes three parameters .The first parameter is the Socket Identifier, 2nd parameter is the address of the server, 3rd is the size of the address.

Here you can assign the server IP with the help of a structure named sockaddr_in

Here is the structure.

struct sockaddr_in

{

short sin_family;

short sin_port;

struct in_addr sin_addr;

char sin_zero[8];

};

We assign a variable P1 of the sockaddr_in type and assign it as follows…

sockaddr_in P1;

P1_addr.sin_family=AF_INET;

P1_addr.sin_addr.S_un.S_un_b.s_b1 =192 ;

P1_addr.sin_addr.S_un.S_un_b.s_b2 =168 ;

P1_addr.sin_addr.S_un.S_un_b.s_b3 =100 ;

P1_addr.sin_addr.S_un.S_un_b.s_b4 =2 ;

Actually here I am giving the IP address of the machine in which the server program is running.

You may use another IP address. But you cant you a random IP it must be the proper IP of the machine in which the server will be running.

After giving the IP address you have to give the port number

P1_addr.sin_port = htons(port);

For binding the socket with the specified IP the code is:

if (bind(Server,(struct sockaddr *)(&P1_addr),sizeof(P1_addr)) == SOCKET_ERROR)

printf("\n\n Attempt to bind failed!!!STOP!!!");

else

printf("\n\n BIND PROCESS IS CREATED SUCCESSFULLY...");

Now it the socket is ready for use? Wait!!! Certainly not, now is it used to tackle any incoming connection? No. It just sets your socket to listening on the specified port, no more no less. listen is a function and it takes two parameters.1st parameter is the socket identifier and 2nd is an integer.

if(listen(Server,5)==SOCKET_ERROR)

printf("\n\n Error in Listenning The Socket!!!STOP!!!");

To accept the incoming connection you use accept (). Here the accept function is placedin side an infinite loop. Because we want to accept connection from any number ofclients. And for giving data to the clients simultaneously we are using thread. It isinteresting to use thread by C programming

while(1)

{

Client=accept(Server,(struct sockaddr*)&cli_addr,&clilen

_beginthread(MyFunction,0,(void *)&Client);

}

MyFunction( void* Arg )

{

SOCKET Client=(*(int *)Arg)

while(1)

{

send(Client,buffer,100,0);

}

}

In C language, you can create a thread by the help of the runtime library function _beginthread(). The _beginthread functions takes three parameters .1st parameter is the name of the function which will be called when the thread is begin.2nd parameter is 0,and the final parameter is the address of Client identifier. It must be type casted into a (void *) The definition of my function is like this (it will be called when the thread begins)

Here in MyFunction takes one parameter and it must be type casted into an int * type. And then it assigns the value into a SOCKET Client. Finally it sends the data to the above- mentioned socket. And gives the data till the client is not close the connection.

How the Client works

The Client Program is self-explanatory. First WinSock has to be initialized. Then in a structure we have to give the server address on which it will be connected later. We have to give also the port number of the server. Then we have created a local socket for connection. We use connect function for connecting with server. connect () function takes three parameters the first one is the socket identifier, address of the structure of server address (Here &P1_addr)is the 2nd. And the size of the P1_addr structure is third. If the connect function returns a non-zero value then we again create a thread in a similar fashion like the server and receives the data in a buffer.

Conclusion

Now I think that you are in a position to write your own socket for your program…

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Pankaj Paul
Software Developer
India India
No Biography provided

Comments and Discussions

 
Questioncompilation error Pinmembersourcecode20129-Sep-12 7:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web01 | 2.8.140902.1 | Last Updated 28 Dec 2006
Article Copyright 2006 by Pankaj Paul
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid