Path: blob/master/07-full-duplex-chat-tcp-ip/server.c
136 views
1/*2* Title : Full duplex server side3* Name : Aditya Pratap Singh Rajput4* Subject : Network Protocols And Programming using C5*6Note : please consider the TYPOS in comments.7Thanks.8*/910#include<sys/types.h>11#include<sys/socket.h>12#include<stdio.h>13#include<unistd.h>14#include<netdb.h>15#include<arpa/inet.h>16#include<netinet/in.h>17#include<string.h>1819int main(int argc,char *argv[])20{21int clientSocketDescriptor,socketDescriptor;2223struct sockaddr_in serverAddress,clientAddress;24socklen_t clientLength;2526char recvBuffer[1000],sendBuffer[1000];27pid_t cpid;28bzero(&serverAddress,sizeof(serverAddress));29/*Socket address structure*/30serverAddress.sin_family=AF_INET;31serverAddress.sin_addr.s_addr=htonl(INADDR_ANY);32serverAddress.sin_port=htons(5500);33/*TCP socket is created, an Internet socket address structure is filled with34wildcard address & server’s well known port*/35socketDescriptor=socket(AF_INET,SOCK_STREAM,0);36/*Bind function assigns a local protocol address to the socket*/37bind(socketDescriptor,(struct sockaddr*)&serverAddress,sizeof(serverAddress));38/*Listen function specifies the maximum number of connections that kernel should queue39for this socket*/40listen(socketDescriptor,5);41printf("%s\n","Server is running ...");42/*The server to return the next completed connection from the front of the43completed connection Queue calls it*/44clientSocketDescriptor=accept(socketDescriptor,(struct sockaddr*)&clientAddress,&clientLength);45/*Fork system call is used to create a new process*/46cpid=fork();4748if(cpid==0)49{50while(1)51{52bzero(&recvBuffer,sizeof(recvBuffer));53/*Receiving the request from client*/54recv(clientSocketDescriptor,recvBuffer,sizeof(recvBuffer),0);55printf("\nCLIENT : %s\n",recvBuffer);56}57}58else59{60while(1)61{6263bzero(&sendBuffer,sizeof(sendBuffer));64printf("\nType a message here ... ");65/*Read the message from client*/66fgets(sendBuffer,10000,stdin);67/*Sends the message to client*/68send(clientSocketDescriptor,sendBuffer,strlen(sendBuffer)+1,0);69printf("\nMessage sent !\n");70}71}72return 0;73}747576