I'd like to send a string with sockets from a client to a server.
Here's the code of the client:
#include <iostream>
#include <winsock.h>
#include <unistd.h>
using namespace std;
int main()
{
//Load socket
WSADATA wsaData;
WSAStartup(0x0202, &wsaData);
//Create first socket
int thisSocket;
struct sockaddr_in destination;
destination.sin_family = AF_INET;
thisSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (thisSocket < 0)
{
cout << "Socket Creation FAILED!" << endl;
return 0;
}
//Connect to a host
destination.sin_port = htons(13374);
destination.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(thisSocket,(struct sockaddr *)&destination,sizeof(destination))!=0){
cout << "Socket Connection FAILED!" << endl;
if (thisSocket) close(thisSocket);
return 0;
}
cout << "Connected!" << endl;
//Send the socket
//char *buffer = "Hello, this is a socket!";
string buffer = "Hello, this is a socket!";
//send(thisSocket, buffer, (int)strlen(buffer), 0);
send(thisSocket, buffer.c_str(), buffer.length(), 0);
//Close the socket
closesocket(thisSocket);
WSACleanup();
}
And here's the code of the server:
#include <iostream>
#include <winsock.h>
#include <unistd.h>
using namespace std;
int main()
{
//Load the socket
WSADATA wsaData;
WSAStartup(0x0202, &wsaData);
//Create the first socket
int thisSocket;
struct sockaddr_in destination;
destination.sin_family = AF_INET;
thisSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (thisSocket < 0)
{
cout << "Socket Creation FAILED!" << endl;
return 0;
}
//Bind to a socket
destination.sin_port = htons (13374);
destination.sin_addr.s_addr = INADDR_ANY;
if (bind(thisSocket, (struct sockaddr *)&destination, sizeof(destination)) <0){
cout << "Binding Socket FAILED!" << endl;
if (thisSocket) close(thisSocket);
return 0;
}
//Listen on a socket
cout << "Listening on 13374..." << endl;
if (listen(thisSocket, 5)<0){
cout << "Listening on Socket FAILED!" << endl;
if (thisSocket) close(thisSocket);
return 0;
}
//Accept a connection
struct sockaddr_in clientAddress;
int clientSize = sizeof(clientAddress);
thisSocket= accept(thisSocket, (struct sockaddr *)&clientAddress, (int *) &clientSize);
if (thisSocket<0)
{
cout << "Socket Connection FAILED!" << endl;
if (thisSocket) close(thisSocket);
return 0;
}
cout <<"Connection Established!" << endl;
//Receive the socket
char buffer[512];
int newData;
newData = recv(thisSocket, buffer, 512, 0);
cout << newData << endl;
//Close the socket
closesocket(thisSocket);
WSACleanup();
}
As you can image, the server will receive the number "24". How can I get the real string instead?