Chat Screenshot

Introduction

In this post, you will learn how to create a simple chat application using Sockets in C!

Getting Started

We will create a server script and a client script (that will connect to the server). We need to first set up the socket on the server side script.

Starting off with a few includes:

#include <stdio.h>
#include <sys/socket.h> //For Sockets
#include <stdlib.h>
#include <netinet/in.h> //For the AF_INET (Address Family)

Now comes the main part, setting up the Socket. So in normal servers, there is a possibility that there can be multiple connections to this server simultaneously. The modification that has to be made so as to accept multiple connections will be using either a pthread or a child process.

struct sockaddr_in serv; //This is our main socket variable.
int fd; //This is the socket file descriptor that will be used to identify the socket
int conn; //This is the connection file descriptor that will be used to distinguish client connections.
char message[100] = ""; //This array will store the messages that are sent by the server

This is the main function:

serv.sin_family = AF_INET;
serv.sin_port = htons(8096); //Define the port at which the server will listen for connections.
server.sin_addr.s_addr = INADDR_ANY;fd = socket(AF_INET, SOCK_STREAM, 0); //This will create a new socket and also return the identifier of the socket into fd.// To handle errors, you can add an if condition that checks whether fd is greater than 0. If it isn't, prompt an errorbind(fd, (struct sockaddr *)&serv, sizeof(serv)); //assigns the address specified by serv to the socketlisten(fd,5); //Listen for client connections. Maximum 5 connections will be permitted.//Now we start handling the connections.while(conn = accept(fd, (struct sockaddr *)NULL, NULL)) {
    int pid;
    if((pid = fork()) == 0) {
        while (recv(conn, message, 100, 0)>0) {
            printf("Message Received: %s\n", message);
            //An extra breaking condition can be added here (to terminate the child process)            
            message = "";
        }
        exit(0);
    }
}

Let’s start populating our client side script. The includes and the variables will be the same as the client side script. I will just be populating the main function below.

fd = socket(AF_INET, SOCK_STREAM, 0);server.sin_family = AF_INET;
server.sin_port = htons(8096);inet_pton(AF_INET, "127.0.0.1", &serv.sin_addr); //This binds the client to localhostconnect(fd, (struct sockaddr *)&serv, sizeof(serv))); //This connects the client to the server.while(1) {
    printf("Enter a message: ");
    fgets(message, 100, stdin);
    send(fd, message, strlen(message), 0);
    //An extra breaking condition can be added here (to terminate the while loop)
}

On running the server and multiple clients, you can now see that each message (sent by multiple clients) is being received by the server simultaneously!

You can now modify the scripts and get parallel reads and writes from the clients and servers. For that, you will have to use pthread as a child process doesn’t share memory with the parent process. It creates a copy of the memory during creation and then acts like a isolated process. Pthreads use the same memory as the parent. Thus, any modifications made in the parent can be accessed in the thread process.

Hope this tutorial was helpful!

What's your reaction?

Excited
0
Happy
0
In Love
0
Not Sure
0
Silly
0

You may also like

Leave a reply

Your email address will not be published.