I am learning winsock2 and set up a very very simple test client-server application (TCP). Basically there is one exe for the server and one exe for the client, each in a separate vc++ 2010 project. Here are the codes for server and client (with error checking and includes removed to shorten)
Server:
int main()
{
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
SOCKET client = INVALID_SOCKET;
SOCKET listener = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in anews;
anews.sin_addr.S_un.S_addr = INADDR_ANY;
anews.sin_family = AF_INET;
anews.sin_port = htons(5001);
bind(listener, (sockaddr*)&anews, sizeof(sockaddr));
listen(listener, SOMAXCONN);
client = accept(listener, NULL, NULL);
send(client, "Hello, client", 13, 0);
std::cout << "sent message" << std::endl;
getchar();
closesocket(client);
closesocket(listener);
WSACleanup();
return 0;
}
Client:
int main()
{
WSADATA wsa;
WSAStartup(MAKEWORD(2, 2), &wsa);
std::string serverIP;
std::cout << "Enter the IP of the server" << std::endl;
std::cin >> serverIP;
SOCKET client = socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in anews;
anews.sin_port = htons(5001);
anews.sin_addr.S_un.S_addr = inet_addr(serverIP.c_str());
anews.sin_family = AF_INET;
while (connect(client, (sockaddr*)&anews, sizeof(sockaddr_in)) == SOCKET_ERROR)
{
std::cout << "Failed to connect to server, retrying..." << std::endl;
}
char buf[100] = {0};
recv(client, buf, 100, 0);
std::cout << buf << std::endl;
getchar();
getchar();
closesocket(client);
WSACleanup();
return 0;
}
So I start the client application, and type "127.0.0.1" for the server IP, to use the loopback interface. THen it displays 'failed to connect' repeatedly, until I start the server application, which then sends the message instantly. THat's all working. It also works if I type my public IP in the client which is something like "144.32.36.186".
However:
Most online games do not need you to manually enter the server IP in order to connect. Even games without dedicated servers, where one of the players is the server. I want to know how I can get my client to automatically find a server, where the server IP can change arbitrarily.
(Then I can try a UDP version )