I am trying to learn winsock ,and I thought I understood it until I tried to make a simple server and client app. I tried to adapt the Source Code from the Winsock 2 for Games article in the Articles section of the site, and I thought I had it working until I tried to connect to my server app from the client. I start the server up and it starts listening for connections. When I execute the client app, it doesn't connect. I have tried everything I can think of, but I cant get it to work, can anyone tell me what I am doing wrong here? Server
#include <iostream.h>
#include <winsock2.h>
#include <stdio.h>
void main ( void )
{
SOCKET s[3];
sockaddr_in me;
sockaddr you[2];
int addr_size = sizeof (sockaddr);
int players_in_lobby = 0;
WSADATA w;
int error = WSAStartup (0x0202,&w);
if (error)
{
cout << "Error: You need WinSock 2.2!\n";
return 0;
}
if (w.wVersion!=0x0202)
{
cout << "Error: Wrong WinSock version!\n";
WSACleanup ();
return 0;
}
s[0] = socket (AF_INET,SOCK_STREAM,0);
me.sin_family = AF_INET;
me.sin_port = htons (1188);
me.sin_addr.s_addr = htonl (INADDR_ANY);
if (bind(s[0],(LPSOCKADDR)&me,sizeof(me))==SOCKET_ERROR)
{
cout << "Error: Unable to bind socket!\n";
WSACleanup ();
return 0;
}
if (listen(s[0],1)==SOCKET_ERROR)
{
cout << "Error: Unable to listen!\n";
WSACleanup ();
return 0;
}
cout << "Listening for connections...\n";
while (players_in_lobby<2)
{
s[players_in_lobby+1] = accept (s[0],&you[players_in_lobby],&addr_size);
if (s[players_in_lobby+1]==INVALID_SOCKET)
{
cout << "Error: Unable to accept connection!\n";
WSACleanup ();
return 0;
}
else
{
cout << "New Player in Lobby!\n";
char buffer[1];
sprintf (buffer,"%c",1);
send (s[players_in_lobby+1],buffer,2,0);
players_in_lobby++;
}
}
}
Client
#include <winsock.h>
#include <stdio.h>
#include <iostream>
#include <cstdio>
bool connected = false;
int main()
{
SOCKET s = socket (AF_INET, SOCK_STREAM, 0); // Create socket
// Must be done at the beginning of every WinSock program
WSADATA w; // used to store information about WinSock version
int error = WSAStartup (0x0202, &w); // Fill in w
if (error)
{ // there was an error
return 0;
}
if (w.wVersion != 0x0202)
{ // wrong WinSock version!
WSACleanup (); // unload ws2_32.dll
return 0;
}
// WSAStartup () has been called
// SOCKET s is valid
// s has been bound to a port using sockaddr_in sock
sockaddr_in you;
you.sin_family = AF_INET; // address family Internet
you.sin_port = htons (1188); // set server’s port number
you.sin_addr.s_addr = inet_addr ("127.0.0.1"); // set server’s IP
if (connect(s,(LPSOCKADDR)&you,sizeof(you))==SOCKET_ERROR)
{
if (WSAGetLastError()==WSAEWOULDBLOCK)
{
Sleep (1000);
connect(s,(LPSOCKADDR)&you,sizeof(you));
return 0;
}
std::cout << error connecting;
}
char buffer[1]; // buffer that is 80 characters big
recv (s, buffer, sizeof(buffer), 0);
std::cout << buffer;
while(true)
{
}
return 0;
}