Sign in to follow this  
chris2307

Beginner to WinSock in need of advice

Recommended Posts

chris2307    163
Hi All,

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

[CODE]
#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;
}
};
[/CODE]

Main.cpp

[CODE]
#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;
}
[/CODE]

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

Share this post


Link to post
Share on other sites
hplus0603    11347
You should think of send() and recv() to take "void *" rather than "char *." The fact that they take "char *" is a historical oddity (back from before the C language had a void type!)

Think of send() and recv() as similar to memcpy() or fwrite(), except the "size" part of it may vary.

Share this post


Link to post
Share on other sites
chris2307    163
Right, okay.

I have just read the FAQ as well and noted question 15. So would I be right in thinking that I can just pass a struct containing all my data to send in one go?

This sounds a little [i]too [/i]easy! [img]http://public.gamedev.net//public/style_emoticons/default/ohmy.png[/img]

Share this post


Link to post
Share on other sites
hplus0603    11347
[quote]This sounds a little too easy![/quote]

It really is that easy (as long as your struct doesn't contain any pointers.)
But when you have that part down, is when the real challenge starts :-)
Also pay attention to the need to prefix all messages with a length, and deal with fragmented packets on the receiving end, if you're using TCP.

Share this post


Link to post
Share on other sites
Khatharr    8812
The only real 'gotcha' is that you need to make sure that any data that you're using as raw numerical data calls something to ensure correct [url="http://en.wikipedia.org/wiki/Endianness"]endianness[/url] (I'd recommend just using the htons/ntohs/htnol/ntohl set that accompanies Winsock/BSD on both ends). Other than that it's pretty similar file to IO. Edited by Khatharr

Share this post


Link to post
Share on other sites
chris2307    163
Brilliant,

Thanks for your help guys. I will be looking in to these "gotchas" soon as well.

Seems a shame that there seems to be a lack of WinSock tutorials out there beyond the "Hello World" apps. (Maybe I am not searching hard enough!)

Share this post


Link to post
Share on other sites
Khatharr    8812
It's mostly because it really [i]is[/i] that simple. If you read through the history of the TCP/IP suite those guys were really aiming at making the bare baseline K.I.S.S. tool for everyone to use however they like. TCP is as complex as they wanted to get. You get to build your own complexity on top of it.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this