One thing that I have always avoided (intentionally or not) is network programming. I have come to the point where I need to have some kind of function that uploads data taken whilst an application runs and upload it to a server. The proper use for this will be to gather research information from players playing a RTC game I am making.
I have looked in to WinSock and have a fair idea of how it works and have created a Server and Client application with the help of the Microfsoft docs. The client and server applications connect to each other (locally for now). The problem I am having is being able to pass in a string to my send function and convert this to the char that is needed to send.
So bascially, what I am after is for my send function to take in one parameter of a string type (i.e. wsClient.Send("Test Message");) and for my recieve function to return the message in string or char form back to my main program. Here is my code:
WinSockClient.h
#include <WinSock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <string>
#pragma comment(lib, "Ws2_32.lib")
class WinSockClient
{
private:
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
WSADATA wsaData;
SOCKET ConnectSocket;
int recvbuflen;
int exitCode;
char recvbuf[DEFAULT_BUFLEN];
struct addrinfo *result,
*ptr,
hints;
public:
WinSockClient()
{
ConnectSocket = INVALID_SOCKET;
addrinfo *result = NULL,
*ptr = NULL;
exitCode = 0;
recvbuflen = DEFAULT_BUFLEN;
}
int Startup()
{
exitCode = WSAStartup(MAKEWORD(2,2), &wsaData);
if(exitCode != 0)
{
printf("WSAStartup failed: %d\n", result);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC; //Unspecified (We can be returned IPv4 or IPv6 addresses)
hints.ai_socktype = SOCK_STREAM; //We're using a stream socket
hints.ai_protocol = IPPROTO_TCP; //We're using the TCP protocol
exitCode = getaddrinfo("192.168.0.2", DEFAULT_PORT, &hints, &result);
if (exitCode != 0)
{
printf("getaddrinfo failed: %d\n", exitCode);
WSACleanup();
return 1;
}
}
int Create()
{
ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
ptr=result;
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
/* Check that socket is valid */
if (ConnectSocket == INVALID_SOCKET)
{
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
}
int Connect(int timeout)
{
/* Connect to server. The application will retry if a connection fails
up until a maximum timeout of 60 second */
exitCode = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
int counter = 0;
while (exitCode == SOCKET_ERROR)
{
printf("Unable to connect to server. Retrying.\n");
counter++;
Sleep(1000);
exitCode = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if(counter == timeout)
break;
}
if(exitCode == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
/* Connection has been made - Free no longer needed resources */
freeaddrinfo(result);
printf("Connection made!\n");
}
int Send(std::string messageIn)
{
const char* messageOut = messageIn.c_str(); // Takes my string and puts it to a const char*
// Send an initial buffer
exitCode = send(ConnectSocket, messageOut, (int) strlen(messageOut), 0); // My message is sent here (???)
if (exitCode == SOCKET_ERROR)
{
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", exitCode);
}
int Recieve()
{
int returnCode = 0;
int messages;
do
{
messages = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (messages > 0)
{
printf("Bytes received: %d\n", messages);
printf("\n", recvbuf, "\n");
returnCode = 0;
messages = 0;
}
else if (messages == 0)
{
returnCode = 1;
}
else
{
printf("recv failed: %d\n", WSAGetLastError());
returnCode = 2;
}
} while (messages > 0);
return returnCode;
}
int ShutdownConnection()
{
exitCode = shutdown(ConnectSocket, SD_SEND);
if (exitCode == SOCKET_ERROR)
{
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
return 0;
}
};
[/CPD#include <WinSock2.h>
#include <ws2tcpip.h>
#include <stdio.h>
#include <string>
#pragma comment(lib, "Ws2_32.lib")
class WinSockClient
{
private:
#define DEFAULT_BUFLEN 512
#define DEFAULT_PORT "27015"
WSADATA wsaData;
SOCKET ConnectSocket;
int recvbuflen;
int exitCode;
char recvbuf[DEFAULT_BUFLEN];
struct addrinfo *result,
*ptr,
hints;
public:
WinSockClient()
{
ConnectSocket = INVALID_SOCKET;
addrinfo *result = NULL,
*ptr = NULL;
exitCode = 0;
recvbuflen = DEFAULT_BUFLEN;
}
int Startup()
{
exitCode = WSAStartup(MAKEWORD(2,2), &wsaData);
if(exitCode != 0)
{
printf("WSAStartup failed: %d\n", result);
return 1;
}
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC; //Unspecified (We can be returned IPv4 or IPv6 addresses)
hints.ai_socktype = SOCK_STREAM; //We're using a stream socket
hints.ai_protocol = IPPROTO_TCP; //We're using the TCP protocol
exitCode = getaddrinfo("192.168.0.2", DEFAULT_PORT, &hints, &result);
if (exitCode != 0)
{
printf("getaddrinfo failed: %d\n", exitCode);
WSACleanup();
return 1;
}
}
int Create()
{
ConnectSocket = socket(result->ai_family, result->ai_socktype, result->ai_protocol);
ptr=result;
ConnectSocket = socket(ptr->ai_family, ptr->ai_socktype,
ptr->ai_protocol);
/* Check that socket is valid */
if (ConnectSocket == INVALID_SOCKET)
{
printf("Error at socket(): %ld\n", WSAGetLastError());
freeaddrinfo(result);
WSACleanup();
return 1;
}
}
int Connect(int timeout)
{
/* Connect to server. The application will retry if a connection fails
up until a maximum timeout of 60 second */
exitCode = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
int counter = 0;
while (exitCode == SOCKET_ERROR)
{
printf("Unable to connect to server. Retrying.\n");
counter++;
Sleep(1000);
exitCode = connect( ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if(counter == timeout)
break;
}
if(exitCode == SOCKET_ERROR)
{
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
/* Connection has been made - Free no longer needed resources */
freeaddrinfo(result);
printf("Connection made!\n");
}
int Send(std::string messageIn)
{
const char* messageOut = messageIn.c_str(); // Takes my string and puts it to a const char*
// Send an initial buffer
exitCode = send(ConnectSocket, messageOut, (int) strlen(messageOut), 0); // My message is sent here (???)
if (exitCode == SOCKET_ERROR)
{
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes Sent: %ld\n", exitCode);
}
int Recieve()
{
int returnCode = 0;
int messages;
do
{
messages = recv(ConnectSocket, recvbuf, recvbuflen, 0);
if (messages > 0)
{
printf("Bytes received: %d\n", messages);
printf("\n", recvbuf, "\n");
returnCode = 0;
messages = 0;
}
else if (messages == 0)
{
returnCode = 1;
}
else
{
printf("recv failed: %d\n", WSAGetLastError());
returnCode = 2;
}
} while (messages > 0);
return returnCode;
}
int ShutdownConnection()
{
exitCode = shutdown(ConnectSocket, SD_SEND);
if (exitCode == SOCKET_ERROR)
{
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
return 0;
}
};
Main.cpp
#include "WinSocketClient.h"
WinSockClient wsClient;
int main()
{
int returnCode;
wsClient.Startup();
wsClient.Create();
if(wsClient.Connect(60) == -1)
{
printf("Connection attempt timedout\n");
wsClient.ShutdownConnection();
return 0;
}
wsClient.Send("Test Message");
while(returnCode = wsClient.Recieve() == 0)
{
Sleep(500);
wsClient.Send("Test Message");
}
if(returnCode == 1)
{
printf("Reply not recieved\n");
}
if(returnCode == 2)
{
printf("RECV error\n");
}
wsClient.ShutdownConnection();
system("PAUSE");
return 0;
}
Any ideas where I am going wrong? I accept that this may be more of a question relating to chars and strings (of which I admit I suffer a weakness on) but I am hoping that some WinSock experts will see this and be able to help me out! :-)
Kind Regrads
Chris