Here is my simplified version of the tcp client, server chat application
client.c
client.c
#include "stdio.h" #include "stdlib.h" #include "sys/types.h" #include "sys/socket.h" #include "arpa/inet.h" int main() { int sockfd,n; char buff[256]; struct sockaddr_in servaddr; //create socket sockfd = socket(AF_INET,SOCK_STREAM,0); //fill serv struct servaddr.sin_family = AF_INET; servaddr.sin_port = htons(40402); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //connect with server connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); //read and write with the server for(;;) { printf("client : "); n=0; while((buff[n++]=getchar())!='\n'); write(sockfd,buff,sizeof(buff)); bzero(buff,sizeof(buff)); //clearing the buffer read(sockfd,buff,sizeof(buff)); printf("server : %s",buff); bzero(buff,sizeof(buff)); } //close close(sockfd); }
server.c
#include "stdio.h" #include "stdlib.h" #include "sys/types.h" #include "sys/socket.h" #include "arpa/inet.h" int main() { int sockfd,connfd,n; char buff[256]; struct sockaddr_in servaddr; //create socket sockfd = socket(AF_INET,SOCK_STREAM,0); //fill server struct servaddr.sin_family = AF_INET; servaddr.sin_port = htons(40402); servaddr.sin_addr.s_addr = inet_addr("127.0.0.1"); //bind bind(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr)); //listen for 1 connection listen(sockfd,1); //accept a client connfd = accept(sockfd,NULL,NULL); //read and write to client for(;;) { read(connfd,buff,sizeof(buff)); printf("client : %s",buff); bzero(buff,sizeof(buff)); printf("server : "); n=0; while((buff[n++]=getchar())!='\n'); write(connfd,buff,sizeof(buff)); bzero(buff,sizeof(buff)); } //close the sockets close(connfd); close(sockfd);
}
Comments
Post a Comment