Establishing a server-client connection for a multiplayer game

am trying to create a chess-like two-person multiplayer game using Microsoft Visual C++. I need some guidance on how to create a connection between the two persons(using the internet). One person will be the server (which will be able to change the properties of the game) and the other one the client. What is the easiest and safest way to establish such a connection and what documentation should I look for?

Thanks a lot.
ChrysaorAsked:
Who is Participating?
 
subn0waCommented:
Easiest way to do that is sockets, look for connect,send,recv,etc. functions family, they are available both in windows and *nix.

And example below.
#include <windows.h>
#pragma comment(lib,"ws2_32.lib")
 
int main(int argc, CHAR* argv[])
{
if(argc != 3)
	return 0;
 
DWORD ip = INADDR_ANY;
 
if(*argv[1] != '0')
	ip = inet_addr(argv[1]);
 
WORD port = htons(atoi(argv[2])); // should be right order of bits;
 
WSADATA wsa;
WSAStartup(0x0202,&wsa);
 
SOCKET s = ::socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(!s)
	return 0;
 
sockaddr_in addra = {0};
addra.sin_family = AF_INET;
addra.sin_port = htons(port);
addra.sin_addr.S_un.S_addr = ip;
int addra_size = sizeof(addra);
 
if(ip == INADDR_ANY) // choose between client and server,
	{
	// its a server part
	bind(s,(sockaddr*)&addra,addra_size); 
	listen(s,5);
	SOCKET client = 0;
	
	// starting a loop for clients
	while( SOCKET_ERROR != (client = accept(s,(sockaddr*)&addra,&addra_size)) )
		{
		// got one
		char buff[513];
		memset(buff,0,513);
 
		recv(client,buff,512,0); // get some data from client. it will be waiting until any data arrives or client disconnects;
		printf(buff); 
		
		//close client socket and wait for another one;
		shutdown(client,0x01);
		closesocket(client);
		}
	}
else
	{
	// its a client part
	if( SOCKET_ERROR != connect(s,(sockaddr*)&addra,addra_size) )
		{
		// send a string after successfull connection.
		send(s,"HELLO,WORLD!",13,0);
 
		//close all and exit
		shutdown(s,0x01);
		closesocket(s);
		
		}
	}
WSACleanup();
return 0;
}

Open in new window

0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.