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.
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