Latest

6/recent/ticker-posts

Write a Client-Server socket program to implement “TCP client server” architecture.

 Write a Client-Server socket program to implement “TCP client server” architecture. 

CODE for server side in c++:



#include < bits/stdc++.h >
#include < sys/socket.h >
#include < netinet/in.h >
using namespace std;
#define PORT 8000

int main()
{
    int server_fd;
    int nRet=0;
    struct sockaddr_in address;
    int opt = 1;
    int addrlen = sizeof(address);
    char buffer[1024] = {0};
    // Socket creation
    server_fd=socket(AF_INET, SOCK_STREAM,0);
    if (server_fd == 0)
    {
        cout << "Socket creation failed" << endl;
        exit(EXIT_FAILURE);
    }
    /*Initialize environment for sockaddr structure*/
    address.sin_family = AF_INET;
    address.sin_addr.s_addr = INADDR_ANY;
    address.sin_port = htons( PORT );
    // Forcefully attaching socket to the port 8080
    nRet=setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT,&opt, sizeof(opt));
    if (nRet)
    {
        cout << "setsockopt Failed" << endl;
        exit(EXIT_FAILURE);
    }
    /*Bind the socket to local port*/
    nRet=bind(server_fd,(struct sockaddr *)&address,sizeof(address));
    if (nRet < 0)
    {
        cout << "Failed to bind"  << endl;
        exit(EXIT_FAILURE);
    }
    //listen request from client
    nRet=listen(server_fd,5);
    if (nRet < 0)
    {
        cout << "Failed to listen" << endl;
        exit(EXIT_FAILURE);
    }
    //accept and process request
    int new_socket=accept(server_fd,(struct sockaddr *)&address,(socklen_t*)&addrlen);
    if (new_socket < 0)
    {
        cout << "Failed to accept request" << endl;
        exit(EXIT_FAILURE);
    }
    //int nread = read( new_socket , buffer, 1024);
    send(new_socket ,"Connection accepted !! Hello from server" , 41 , 0 );
    cout << "Connection successfull" << endl;
    return 0;
}


CODE for client side in c++:


#include <bits/stdc++.h >
#include <sys/socket.h >
#include < arpa/inet.h >
#include < unistd.h >
#define PORT 8080

int main()

{
    int sock = 0, valread;
    struct sockaddr_in serv_addr;
    char buffer[1024] = {0};
    if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        printf("\n Socket creation error \n");
        return -1;
    }
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_port = htons(PORT);
    // Convert IPv4 and IPv6 addresses from text to binary form
    if(inet_pton(AF_INET, "127.0.0.1", &serv_addr.sin_addr) < =0) 
    {
        printf("\nInvalid address/ Address not supported \n");
        return -1;
    }
    if (connect(sock, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0)
    {
        printf("\nConnection Failed \n");
        return -1;
    }
    valread = read( sock , buffer, 1024);
    printf("%s\n",buffer );
    return 0;

}











Post a Comment

0 Comments