Client Stages
Similar to server, we also have to create a socket and specify the address. But instead of accepting request, we send the connection request when we can to sent the data using connect() call.
Then we sent the data using send() call. After all the operations are done, we close the connection using close() call.
1. Creating the Client Socket
int clientSocket = socket(AF_INET, SOCK_STREAM, 0);
2. Defining Server Address
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(8080);
serverAddress.sin_addr.s_addr = INADDR_ANY;
3. Connecting to the Server
connect(clientSocket, (struct sockaddr*)&serverAddress, sizeof(serverAddress));
4. Sending Data to the Server
const char* message = "Hello, server!";
send(clientSocket, message, strlen(message), 0);
5. Closing the Client Socket
close(clientSocket);
Socket Programming in C++
In C++, socket programming refers to the method of communication between two sockets on the network using a C++ program. We use the socket API to create a connection between the two programs running on the network, one of which receives the data by listening to the particular address port, and the other sends the data. One of the features of the socket programming is that it allows the bidirectional communication between the nodes.
In this article, we will create some simple C++ programs to demonstrate the use of socket programming.
Contact Us