Jump to content

  • Log In with Google      Sign In   
  • Create Account


Beginner to WinSock in need of advice


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
6 replies to this topic

#1 chris2307   Members   -  Reputation: 163

Like
0Likes
Like

Posted 11 November 2012 - 03:45 PM

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

#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

Sponsor:

#2 hplus0603   Moderators   -  Reputation: 4960

Like
0Likes
Like

Posted 11 November 2012 - 10:01 PM

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.
enum Bool { True, False, FileNotFound };

#3 chris2307   Members   -  Reputation: 163

Like
0Likes
Like

Posted 12 November 2012 - 05:38 AM

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 too easy! Posted Image

#4 hplus0603   Moderators   -  Reputation: 4960

Like
0Likes
Like

Posted 12 November 2012 - 12:09 PM

This sounds a little too easy!


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.
enum Bool { True, False, FileNotFound };

#5 Khatharr   Crossbones+   -  Reputation: 2818

Like
0Likes
Like

Posted 13 November 2012 - 04:35 PM

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 endianness (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, 13 November 2012 - 04:53 PM.

void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.

#6 chris2307   Members   -  Reputation: 163

Like
0Likes
Like

Posted 14 November 2012 - 02:59 PM

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!)

#7 Khatharr   Crossbones+   -  Reputation: 2818

Like
0Likes
Like

Posted 14 November 2012 - 06:38 PM

It's mostly because it really is 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.
void hurrrrrrrr() {__asm sub [ebp+4],5;}

There are ten kinds of people in this world: those who understand binary and those who don't.




Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS