0% found this document useful (0 votes)
4 views7 pages

5.c.write A Socket Programming (Multi Client - Server Model)

The document outlines the implementation of a multi-client server socket program that can handle multiple client requests simultaneously. It provides detailed algorithms for both the server and client, emphasizing the use of multi-threading, forking, and asynchronous I/O for efficient communication. The code examples demonstrate the setup and operation of the server and client applications, confirming successful communication between them.

Uploaded by

Anand Duraiswamy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views7 pages

5.c.write A Socket Programming (Multi Client - Server Model)

The document outlines the implementation of a multi-client server socket program that can handle multiple client requests simultaneously. It provides detailed algorithms for both the server and client, emphasizing the use of multi-threading, forking, and asynchronous I/O for efficient communication. The code examples demonstrate the setup and operation of the server and client applications, confirming successful communication between them.

Uploaded by

Anand Duraiswamy
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Experiment 5.

b: Multi Client - Server Socket Programming

Aim:

To create a multi server socket program that can handle multiple


client requests simultaneously using sockets.

Server Algorithm:

1. Start the program.


2. Create a socket using socket() system call.
3. Bind the socket with IP address and port number using
bind().
4. Listen for incoming client connections using listen().
5. Accept the client connection using accept().
6. When a client connects, create a separate process/thread to
handle that client.
7. Receive message from client using recv()/read().
8. Process the request and send response using send()/write().
9. Continue accepting multiple clients simultaneously.
10. Close the socket after communication ends.
11. Stop the program.

Client Algorithm:

1. Start the program.


2. Create a socket using socket().
3. Specify the server IP address and port number.
4. Connect the client to the server using connect().
5. Multiple clients run the client program simultaneously.
6. Send messages to the server using send()/write().
7. Receive response from server using recv()/read().
8. Continue communication until the client stops.
9. Close the socket connection.
10. Stop the program.

Theory:

Multi Server Socket Programming is used to communicate with


multiple clients at the same time.
In normal single server socket programming, the server can
communicate with only one client at a time. But in multi server,
the server can handle many clients simultaneously.

This is achieved using techniques such as:

 Multi-threading
 Fork (multiple processes)
 Asynchronous I/O

Each client request is handled by a separate thread or process,


so multiple clients can communicate with the server without
waiting.

This method is commonly used in:

 Web servers
 Chat servers
 Online games
 Database servers

Multi Server Program:

//[Link]

#include <stdio.h>
#include <winsock.h>

#define PORT 99991

int nSocket;
int nClientSocket[5] = { 0, };
struct sockaddr_in srv;
fd_set fr;
fd_set fw;
fd_set fe;
int nMaxFd = 0;

void HandleNewConnection()
{

//nNewClient will be a new file descriptor


//and now the client communication will take place
//using this file descriptor/socket only
int nNewClient = accept(nSocket, NULL, NULL);

//If you accept the value in second parameter, then it


//will be

if (nNewClient < 0)
{
printf("Not able to get a new client socket\n");
}
else
{
int nIndex;
for (nIndex = 0; nIndex < 5; nIndex++)
{
if(nClientSocket[nIndex] == 0)
{
nClientSocket[nIndex] = nNewClient;
if(nNewClient > nMaxFd)
{
nMaxFd = nNewClient + 1;
}
break;
}
}

if(nIndex == 5)
{
printf("Server busy. Cannot accept anymore connections\n");
}
}
}

void HandleDataFromClient()
{
for(int nIndex = 0; nIndex < 5; nIndex++)
{
if(nClientSocket[nIndex] > 0)
{
if(FD_ISSET(nClientSocket[nIndex], &fr))
{
//Read the data from client
char sBuff[255] = { 0, };
int nRet = recv(nClientSocket[nIndex], sBuff, 255, 0);
if(nRet < 0)
{
//This happens when client closes connection abruptly
printf("Error at client socket\n");
closesocket(nClientSocket[nIndex]);
nClientSocket[nIndex] = 0;
}
else
{
printf("\nReceived data from: %d [Message:
%s]",nClientSocket[nIndex],
sBuff);
break;
}
}
}
}
}

//Multiclient [5]: A server which can handle more than one


client
//connection at a time simultaneously

int main()
{
int nRet = 0;
WSADATA wd;
if(WSAStartup(MAKEWORD(2, 2), &wd) < 0)
{
printf("Not able to start the socket environment\n");
return(EXIT_FAILURE);
}

//Listener socket
nSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if(nSocket < 0)
{
printf("The socket cannot be initialized\n");
exit(EXIT_FAILURE);
}

srv.sin_family = AF_INET;
srv.sin_port = htons(PORT); //MSB first
srv.sin_addr.s_addr = INADDR_ANY; //Only for server
memset(&srv.sin_zero, 0, 8);

nRet = bind(nSocket, (struct sockaddr*)&srv, sizeof(struct


sockaddr));
if(nRet < 0)
{
printf("The socket cannot be bind\n");
exit(EXIT_FAILURE);
}

nRet = listen(nSocket, 5);


if(nRet < 0)
{
printf("The listen failed");
exit(EXIT_FAILURE);
}

struct timeval tv;


tv.tv_sec = 1;
tv.tv_usec = 0;

//One is listener socket


//There could be new clients which could send you message
after //connection
//fd_set fr;

nMaxFd = nSocket + 1;

while(1)
{
//Set the FD_SET.
//This need to be done every time

FD_ZERO(&fr);
FD_SET(nSocket, &fr);
for(int nIndex = 0; nIndex < 5; nIndex++)
{
if(nClientSocket[nIndex] > 0)
{
FD_SET(nClientSocket[nIndex], &fr);
}
}

nRet = select(nMaxFd, &fr, NULL, NULL, &tv);

//After above call, every bit is reset by select call in fr

if(nRet < 0)
{
printf("select api call failed. Will exit\n");
return (EXIT_FAILURE);
}
else if (nRet == 0)
{
printf("No client at port waiting for an active connection/new
message\n");
}
else
{
//There is some client waiting either to connect
//or some new data came from existing client.
if(FD_ISSET(nSocket, &fr))
{
//Handle New connection
HandleNewConnection();
}
else
{
//Check what existing client got the new data
HandleDataFromClient();
}
}
}
}

Multi Client Program:

//[Link]

#include <stdio.h>
#include <winsock.h>
#define PORT 99991

int main()
{
//Initiate the Socket environment
WSADATA w;
int nRet = 0;

sockaddr_in srv;

nRet = WSAStartup(MAKEWORD(2, 2), &w);


if (nRet < 0)
{
printf("\nCannot Initialize socket lib");
return -1;
}
//Open a socket - listener
int nSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (nSocket < 0)
{
//errno is a system global variable which gets updated
//with the last API call return value/result.
printf("\nCannot Initialize listener socket:%d",
errno);;
return -1;
}

srv.sin_family = AF_INET;
srv.sin_addr.s_addr = inet_addr("[Link]");
srv.sin_port = htons(PORT);
memset(&(srv.sin_zero), 0, 8);

nRet = connect(nSocket, (struct sockaddr*)&srv,


sizeof(srv));
if (nRet < 0)
{
printf("\nCannot connect to server:%d", errno);;
return -1;
}

//Keep sending the messages


char sBuff[1024] = { 0, };
while (1)
{
Sleep(2000);
printf("\nWhat message you want to send..?\n");
fgets(sBuff, 1023, stdin);
send(nSocket, sBuff, strlen(sBuff), 0);
}
}

Result:

Thus, the communication between multi client and server using


socket programming was executed and verified successfully.

You might also like