top of page

Socket Programming: I am your client.

Updated: May 1, 2020

Welcome folks...


In the last article, we saw how to create a server and open a socket. I will highly recommend going through Socket Programming: Where is my server? article before proceeding to this article.


In this article, we will see how to create a client which will connect to our server and send a message.

Let's begin...

client.cpp is here.


To connect to a server, the client requires a socket. So here it is our client socket.

int clientSocket = socket(AF_INET, SOCK_STREAM, 0);

All the parameters are the same as for the server socket. For an explanation please go to the server.

Now once the socket is created successfully,

We will create a sockaddr_in object which will have family, port and address.

sockaddr_in clientSockAdd;
clientSockAdd.sin_family= AF_INET;
clientSockAdd.sin_port= htons(PortNumber);
inet_pton(AF_INET, "127.0.0.1", &clientSockAdd.sin_addr);

We are using 127.0.0.1, it is a loopback address. In our example, both the client and the server are going to run on the same machine. If you want to run on different machines, Please provide an IP address of your server machine.


Hey I hope you know htons() and inet_pton() function.


Once you have sockaddr_in object, let's connect our client socket with this address.

int ret = connect(clientSocket,(sockaddr*)&clientSockAdd, sizeof(clientSockAdd));

On a successful connection, we will start a do-while() loop.

In this loop, we will first ask the client/user to enter any string.

cout << "$ ";
getline(cin, clientInput);

Once we have a string in the buffer, let's send it to the server using send() function.

int retSend = send(clientSocket, clientInput.c_str(), clientInput.size()+1, 0);

To keep this program a bit simple, the server will return the same message to the client. Let's receive that.

int SizeOfResponseRecvFromServer = recv(clientSocket, buffer, 1024, 0);

If we received a valid message from the server, we can print it on the console.

While loop is an infinite loop, so it will run until the user close the application.

Its time to close the client socket on exit.

close(clientSocket);

This is all about the basic of socket programming. In future, I will write a chit-chat application in which 2 different clients will be able to communicate with each other.


Till I post my next article, please share this blog with others who want to learn socket programming.

Comments


© 2023 by Dheeraj Jha

bottom of page