Socket Programming with threads
In this Article I have written what I have done in my project i.e. Client server communication using posix threads and socket.
In this project i made a server which can accept connections from more then one clients. As soon as the clients connect to the server they are able to send or /and receive files from the server and communicate with them. In this i use two protocols that are UNIX which is used to communicate within a system means two process on the same system can communicate with each other , Second one is INET which is used to communicate between two or more than two process over the network.
We use tcp/ip in the socket as it is the secure method of file transfer as in this ,first the secure connection is established and then data is transferred.
In this project I also used threads so that process can worked concurrently independent of each other.If we dont have network,then also we can check whether our socket for over the network will work or not,with the help of loop back address (127.0.0.1).
Process of creating Server side:
I am explaining here System calls for creating server:
1.Socket: This system call is used to create a socket and return a file descriptor on success.In the socket call we also specify type of socket,whether its is for UNIX or whether for INET.
We also specify here which type is used, SOCK_STREAM, which is a used to reliable,two way connections and another one is SOCK_DGRAM which is not reliable as it is connection less.
In this we also give the protocol by which the file is going to transfer (tcp / udp).
2.bind: This is usually for giving name and assigning port to the socket.
3.listen:It creates a queue for upcoming clients listen(sockfd,backlog).
4.accept:In accept the most important work is done that is to connect with a client and assign him a dedicated fd so that it can work on it.
Process of client side:
1.Socket;Same work as of server side.
2Connect: This is used to request to the server to connect so that communication is made between two.
Between this we also have to give port and address on which this socket will work.
Now,after the connection is established , we are ready to communicate,i use read and write system calls to communicate between two. Using threads i made two process one for read and another for write so that both server and client run concurrently,without the interference of each other,I just pass the file descriptor as the argument there.
After this i made a project in which 2 clients used to communicate each other with the help of server , means first data from one client goes to server and then server write it to another client and it will read that.
I made an another project where first authentication is requires ,when authenticate then server will able to connect with another client. In this server asked for a password ,if matches then it will work.