TCP Chat - Transmission Control Protocol - Networks & DBMS Lab - C Program




Program:

(tcpserver.c)


// TCP Chat : Server

#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
    struct sockaddr_in client,server;
    int s,n,sock;
    char b1[100]="",b2[100]="2k8cs.tk";
    s=socket(AF_INET,SOCK_STREAM,0);
    server.sin_family=AF_INET;
    server.sin_port=2000;
    server.sin_addr.s_addr=inet_addr("127.0.0.1");
    bind(s,(struct sockaddr *)&server,sizeof server);
    listen(s,1);
    printf("\nServer ready,waiting for client....\n");
    n=sizeof client;
    sock=accept(s,(struct sockaddr *)&client,&n);
 
    for(;;)
    {
        recv(sock,b1,sizeof b1,0);
        if(strcmp(b1,"end")==0)
            break;
        printf("\nClient:%s",b1);
        printf("\nServer:");
        gets(b2);
        send(sock,b2,sizeof b2,0);
        if(strcmp(b2,"end")==0)
            break;
     
    }
    close(sock);
    close(s);
}


(tcpclient.c)

// TCP Chat : Client

#include<stdio.h>
#include<string.h>
#include<sys/stat.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
main()
{
    struct sockaddr_in client,server;
    int s,sock;
    char b1[100]="",b2[100]="2k8cs.tk";
    s=socket(AF_INET,SOCK_STREAM,0);
    server.sin_family=AF_INET;
    server.sin_port=2000;
    server.sin_addr.s_addr=inet_addr("127.0.0.1");
    printf("\nClient ready....\n");
    connect(s,(struct sockaddr *)&server,sizeof server);
    for(;;)
    {
        printf("\nClient:");
        gets(b2);
        send(s,b2,sizeof b2,0);
        if(strcmp(b2,"end")==0)
            break;
        recv(s,b1,sizeof b1,0);
        if(strcmp(b1,"end")==0)
            break;
        printf("\nServer:%s",b1);
    }
    close(s);
}
Output:

Terminal 1: (Server)

nn@linuxmint ~ $ gcc tcps.c -o server
/tmp/cch4cSzA.o: In function `main':
tcps.c:(.text+0x18e): warning: the `gets' function is dangerous and should not be used.
nn@linuxmint ~ $ ./server

Server ready,waiting for client....

Client:hi,2k8618...
Server:hi...

Client:your site is helpful...
Server:thanks

Client:ok.bye...
Server:bye
nn@linuxmint ~ $


Terminal 2: (Client)

nn@linuxmint ~ $ gcc tcpc.c -o client
/tmp/cc73fkiv.o: In function `main':
tcpc.c:(.text+0xf2): warning: the `gets' function is dangerous and should not be used.
nn@linuxmint ~ $ ./client

Client ready....

Client:hi,2k8618...

Server:hi...
Client:your site is helpful...

Server:thanks
Client:ok.bye...

Server:bye
Client:end
nn@linuxmint ~ $

1 comment:

Related Posts Plugin for WordPress, Blogger...