AIM:
To write a program for TCP chat between client and server.
ALGORITHM:
SERVER:
STEP 1: Start
STEP 2: Declare the variables for the socket
STEP 3: Specify the family, protocol, IP address and port number
STEP 4: Create a socket using socket() function
STEP 5: Bind the IP address and Port number
STEP 6: Listen and accept the client’s request for the connection
STEP 7: Read the client’s message
STEP 8: Display the client’s message
STEP 9: Continue the chat
STEP 10: Terminate the chat
STEP 11: Close the socket
STEP 12: Stop
CLIENT:
STEP 1: Start
STEP 2: Declare the variables for the socket
STEP 3: Specify the family, protocol, IP address and port number
STEP 4: Create a socket using socket() function
STEP 5: Call the connect() function
STEP 6: Read the input message
STEP 7: Send the input message to the server
STEP 8: Display the server’s reply
STEP 9: Continue the chat
STEP 10: Terminate the chat
STEP 11: Close the socket
STEP 12: Stop
SOURCE CODE:
SERVER:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define SERV_TCP_PORT 5035
int main(int argc,char**argv)
{
int sockfd,newsockfd,clength;
struct sockaddr_in serv_addr,cli_addr;
char buffer[4096];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=INADDR_ANY;
serv_addr.sin_port=htons(SERV_TCP_PORT);
bind(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
listen(sockfd,5);
clength=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr*)&cli_addr,&clength);
read(newsockfd,buffer,4096);
while(buffer!="quit")
{
printf("\nClient message: %s",buffer);
printf("\nType your message : ");
fgets(buffer,4096,stdin);
write(newsockfd,buffer,4096);
printf("\n");
read(newsockfd,buffer,4096);
}
close(sockfd);
return 0;
}
CLIENT:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#define SERV_TCP_PORT 5035
int main(int argc,char**argv)
{
int sockfd;
struct sockaddr_in serv_addr;
struct hostent *server;
char buffer[4096];
sockfd=socket(AF_INET,SOCK_STREAM,0);
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
serv_addr.sin_port=htons(SERV_TCP_PORT);
connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
printf("\nEnter the message to send : ");
fgets(buffer,4096,stdin);
fputs(buffer,stdout);
while(buffer!="quit")
{
if(buffer=="quit")
break;
write(sockfd,buffer,4096);
read(sockfd,buffer,4096);
printf("\n");
printf("\nServer message:\t%s",buffer);
printf("\nType your message:\t");
fgets(buffer,4096,stdin);
}
close(sockfd);
return(0);
}
OUTPUT:
SERVER:
CLIENT:
RESULT:
Thus the program for TCP chat between client server was executed and the output was verified.
EmoticonEmoticon