• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
chris2307

Beginner to WinSock in need of advice

6 posts in this topic

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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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]
0

Share this post


Link to post
Share on other sites
[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.
0

Share this post


Link to post
Share on other sites
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
0

Share this post


Link to post
Share on other sites
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!)
0

Share this post


Link to post
Share on other sites
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.
0

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  
Followers 0