Question

In: Computer Science

I am needing to initialize a server socket and wait for incoming connections in C programming....

I am needing to initialize a server socket and wait for incoming connections in C programming. I am also required to create a thread to handle my client and able to pass messages between them asynchronously. I would ideally like to start my server with pthreads to allow for multiple connections.

I have 2 functions started:

int serverRun(){

this will be the meat of the server code with sockets

}

int serverStart()

{

This is where I want to initiate the server

}

Solutions

Expert Solution

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<unistd.h>
#include<pthread.h>
 
// initialise functions and variables
void *connection_handler(void *);
int socket_desc , client_sock , c;
struct sockaddr_in server , client;
pthread_t thread_id;
     
int serverRun()
{
    listen(socket_desc , 3);

    //Accept and incoming connection
    printf("Waiting for incoming connections...\n");
    c = sizeof(struct sockaddr_in);
     
    //Accept and incoming connection
    printf("Waiting for incoming connections...\n");
    c = sizeof(struct sockaddr_in);
        
    while( (client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c)) )
    {
        printf("Connection accepted\n");
         
        if( pthread_create( &thread_id , NULL ,  connection_handler , (void*) &client_sock) < 0)
        {
            printf("Could not create thread\n");
            return 1;
        }
         
        //Now join the thread , so that we dont terminate before the thread
        //pthread_join( thread_id , NULL);
        printf("Handler assigned\n");
    }
     
    if (client_sock < 0)
    {
        printf("accept failed\n");
        return 1;
    }
}
int serverStart()
{
    //Create server socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1)
    {
        printf("Could not create socket\n");
        return 0;
    }
    printf("Server Socket Created\n");
     
    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons(8000); // You can use any port here
     
    //Bind the port to the server socket to be active listner
    if( bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0)
    {
        printf("bind failed\n");
        return 0;
    }
    printf("bind done\n");
    return 1;
}
 
int main(int argc , char *argv[])
{
    int serverStatus = serverStart();
    if(serverStatus = 1)
    {
        printf("Server Created\n");
    }
    else
    {
        printf("Server Creation failed\n");
    }
    int a = serverRun();

    return 0;
}
 
/*
 * This will handle connection for each client
 * */
void *connection_handler(void *socket_desc)
{
    //Get the socket descriptor
    int sock = *(int*)socket_desc;
    int read_size;
    char *message , client_message[2000];
     
    //Send some messages to the client
    message = "Greetings! I am your connection handler\n";
    write(sock , message , strlen(message));
     
    message = "Now type something and i shall repeat what you type \n";
    write(sock , message , strlen(message));
     
    //Receive a message from client
    while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 )
    {
        //end of string marker
                client_message[read_size] = '\0';
                
                //Send the message back to client
        write(sock , client_message , strlen(client_message));
                
                //clear the message buffer
                memset(client_message, 0, 2000);
    }
     
    if(read_size == 0)
    {
        printf("Client disconnected\n");
        fflush(stdout);
    }
    else if(read_size == -1)
    {
        printf("recv failed\n");
    }
         
    return 0;
} 

Here is the required c c0de for server


Related Solutions

I am trying to write a UDP socket program in which there is a server program...
I am trying to write a UDP socket program in which there is a server program and a client program. This is what I have but I can't figure out where I am going wrong. This is the input and expected output: > gcc udpclient.c –o clientout > gcc udpserver.c –o serverout > ./serverout 52007 ‘to celebrate’ & > ./clientout odin 52007 ‘Today is a good day’ Today is a good day to celebrate //UDP echo client program #include #include...
I am new to socket programming and I wish to know what these lines of code...
I am new to socket programming and I wish to know what these lines of code do. I know they are creating UDP sockets, but it would help if someone explained what the code means. Thank you. Python Code: import socket testingSocket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) testingSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, testingSocket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) testingSocket.bind(('0.0.0.0', 50000)) send_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) send_socket.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1) receiving_thread = Thread(target=self.receivingFunction) send_thread = Thread(target=self.sendMessage) broadcast_online_status_thread = Thread(target=onlineStatus)
In this homework, you will practice and reinforce the basics of socket programming for TCP connections...
In this homework, you will practice and reinforce the basics of socket programming for TCP connections in Python: how to create a socket, bind it to a specific address and port, as well as send and receive a HTTP packet. You will also learn some basics of HTTP header format. The requirements for this homework are specified below. 1. Function Requirement: You will develop a web server that handles one HTTP request at a time. Your web server should accept...
TCP client and server using C programming I am having trouble on how to read in...
TCP client and server using C programming I am having trouble on how to read in the IP adress and port number from the terminal Example: Enter IP address: 127.0.0.1 Enter Port Number: 8000 in both client and server code. How do can I make I can assign the Ip address and port number using the example above. the error I get is that the client couldn't connect with the server whenever i get the port number from the user...
I am needing assistance figuring out how to write the code for this project in C#...
I am needing assistance figuring out how to write the code for this project in C# (C sharp)... Create a new Project and name it - InClassParticipation3 Get up to 5 inputs from the user. The user must enter at least 1 number. After the first input, ask them if they would like to input another number if they say 'yes' get the provided input and multiply it to the other inputs provided by the user. If the user says...
In C programming, I am trying to search for the names of people that in this...
In C programming, I am trying to search for the names of people that in this DOISigned.txt file, however I am having trouble getting the first and last names of the multiple people named john, my current code only searches for John once and then it terminates,here is my current code #define _CRT_SECURE_NO_WARNINGS #include <stdio.h> #include <string.h> #include <stdlib.h> #define BUF_SIZE 0x3000 char buf[BUF_SIZE]; int main() {    char* inputFile = "DOISigners.txt";    FILE* fp;    fp = fopen(inputFile, "r");...
C programming language. **I am aware that I am only supposed to ask one question so...
C programming language. **I am aware that I am only supposed to ask one question so if you cant do all of this could you please do part 2? thank you! This lab, along with your TA, will help you navigate through applying iterative statements in C. Once again we will take a modular approach to designing solutions to the problem below. As part of the lab you will need to decide which C selection structure and iterative structure is...
C programming language. **I am aware that I am only supposed to ask one question so...
C programming language. **I am aware that I am only supposed to ask one question so if you cant do all of this could you please do part 3? thank you! This lab, along with your TA, will help you navigate through applying iterative statements in C. Once again we will take a modular approach to designing solutions to the problem below. As part of the lab you will need to decide which C selection structure and iterative structure is...
The Question I am needing assistance with is in BOLD BELOW. I will include the other...
The Question I am needing assistance with is in BOLD BELOW. I will include the other aspects of this assignment for reference, as well as the table used/needed for these calculations. Option #1: Critical Thinking: Quality at A1 Hotels A1 Hotels operates luxury hotels throughout the world. Recently, motivated by some incidents that appeared in the news, they have been concerned about the quality of service. The company has been giving the following survey to its clients after their stay:...
Greetings, Consider a client server model.The server sends the message 'I am the server' to client....
Greetings, Consider a client server model.The server sends the message 'I am the server' to client. Describe and compare in details how the client and server exchange these messages using internet domain in the following two modes. a) connection-oriented modes b) connectionless-oriented modes
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT