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