multiple connections in UDP server

Started by
11 comments, last by hplus0603 11 years, 8 months ago
Hey,
I've been searching a lot and found out that the server based on UDP should have only 1 socket that is doing all the job for every single client. And each client should have his own socket bound to unique port but can exist on the same ip? I'm trying to run a server and connect to it more than 1 client. 1 client connects normally but I can't bind the socket for the second client. Everything takes place on one the same PC and the server is localhost. The same code is used to create and bind a socket both for server and client(and comes from gafferongames.com):

bool Open( unsigned short port )
{
assert( !IsOpen() );

// create socket
socket = ::socket( AF_INET, SOCK_DGRAM, IPPROTO_UDP );
if ( socket <= 0 )
{
printf( "failed to create socket\n" );
socket = 0;
return false;
}
// bind to port
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( (unsigned short) port );

if ( bind( socket, (const sockaddr*) &address, sizeof(sockaddr_in) ) < 0 )
{
printf( "failed to bind socket\n" ); //!!!!!!!!!!!!! - this message pops up when trying to connect with second client
Close();
return false;
}
// set non-blocking io
#if PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX

int nonBlocking = 1;
if ( fcntl( socket, F_SETFL, O_NONBLOCK, nonBlocking ) == -1 )
{
printf( "failed to set non-blocking socket\n" );
Close();
return false;
}

#elif PLATFORM == PLATFORM_WINDOWS

DWORD nonBlocking = 1;
if ( ioctlsocket( socket, FIONBIO, &nonBlocking ) != 0 )
{
printf( "failed to set non-blocking socket\n" );
Close();
return false;
}
#endif

return true;
}


What could be the issue? I'm a real beginner and really can't find the solution so I would be very grateful for any advice!
Advertisement
If you try binding two sockets to the same IP and port then the second attempt will fail. The question is why are you binding a client socket in the first place? If you don't bind the socket, the system should automatically assign a unique port to each socket.
1) create socket.
2) send connection request to host.
3) listen for reply.

option :
1a) bind to port 0. That will tell the system to bind to an arbitrary port.

Everything is better with Metal.

actually I'm quite confused with those ports. I was assigning a port for client just at the beginning of int main() like this:
srand();
int client_port = rand()%20000 + 1025;
I thought that every enxt client ran will have different port so maybe it's not a problem? However I realise that this solution is really bad and therefore I would like to ask how should I apply port to clients? To make them always unique and non problematic?


If you don't bind the socket, the system should automatically assign a unique port to each socket.

What do you mean? I don't have to bind a socket for each client?

edit: yeah, now the client doesn't fail on creating and binding a socket! Thanks papalazaru. However now I'm having some problems connected with sending and receving to multiple clients and vice versa. I'll have to see the code deeper later
Only the server should bind to a port, so that the clients know how to connect.
The clients should just create the socket, and then sendto() the server. This will make the computer bind to some ready, available, port, at the first send.
Also, the server shouldn't "connect to" the clients, because that will fail through NAT gateways. The first datagram should go from client to server, and the server should use recvfrom() to get the client address (ip/port) and any traffic back to that client should use that ip/port.
A recvfrom() from a ip/port you haven't seen before is going to be a new client. There are some rare conditions where an existing client may change its ip/port, but that's not something you generally need to deal with other than telling the "new" client that you don't know about it and it needs to re-login.
enum Bool { True, False, FileNotFound };
hmm alright. The code in gafferongames tutorial is a bit too complex for me atm so I tried creating my own simple client and server programs. But I can't seem to make it work. Here's my client code:
// platform detection
#define PLATFORM_WINDOWS 1
#define PLATFORM_MAC 2
#define PLATFORM_UNIX 3
#if defined(_WIN32)
#define PLATFORM PLATFORM_WINDOWS
#elif defined(__APPLE__)
#define PLATFORM PLATFORM_MAC
#else
#define PLATFORM PLATFORM_UNIX
#endif
#if PLATFORM == PLATFORM_WINDOWS
#include <winsock2.h>
#pragma comment( lib, "wsock32.lib" )
#elif PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#else
#error unknown platform!
#endif
#include <assert.h>
#include <vector>
#include <map>
#include <stack>
#include <list>
#include <algorithm>
#include <functional>
const int ServerPort = 30000;
int main()
{
unsigned int server_ip = 0;
server_ip = (127 << 24) | (0 << 16) | (0<< 8) | 1;
#if PLATFORM == PLATFORM_WINDOWS
WSADATA WsaData;
if(WSAStartup( MAKEWORD(2,2), &WsaData ) < 0)
{
printf("Failed to initialise");
return 1;
}
#else
return true;
#endif
SOCKET ClientSocket;
ClientSocket = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = htonl(server_ip);
address.sin_port = htons(unsigned short(ServerPort));
sockaddr_in from;
while(1)
{
char buffer[256] = "Give me data";
int sent_bytes = sendto(ClientSocket, buffer, strlen(buffer), 0, (sockaddr*)&address, sizeof(sockaddr_in));
if(sent_bytes != strlen(buffer))
{
printf("Nothing sent");
break;
}
char receive[256] = "";
int bytes_received = recvfrom(ClientSocket, receive, 256, 0, (sockaddr*)&from, (int *)sizeof(sockaddr_in));
if(bytes_received > 0)
printf("%s", receive);
Sleep(500);
}
}

and here's server's code:

// platform detection
#define PLATFORM_WINDOWS 1
#define PLATFORM_MAC 2
#define PLATFORM_UNIX 3
#if defined(_WIN32)
#define PLATFORM PLATFORM_WINDOWS
#elif defined(__APPLE__)
#define PLATFORM PLATFORM_MAC
#else
#define PLATFORM PLATFORM_UNIX
#endif
#if PLATFORM == PLATFORM_WINDOWS
#include <winsock2.h>
#pragma comment( lib, "wsock32.lib" )
#elif PLATFORM == PLATFORM_MAC || PLATFORM == PLATFORM_UNIX
#include <sys/socket.h>
#include <netinet/in.h>
#include <fcntl.h>
#else
#error unknown platform!
#endif
#include <assert.h>
#include <vector>
#include <map>
#include <stack>
#include <list>
#include <algorithm>
#include <functional>
const int ServerPort = 30000;
int main()
{
#if PLATFORM == PLATFORM_WINDOWS
WSADATA WsaData;
if(WSAStartup( MAKEWORD(2,2), &WsaData ) < 0)
{
printf("Failed to initialise");
return 1;
}
#else
return true;
#endif
SOCKET ServerSocket;
ServerSocket = socket(AF_INET, SOCK_DGRAM, 0);
sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons( (unsigned short) ServerPort );
bind(ServerSocket, (sockaddr*)&address, sizeof(sockaddr_in));
sockaddr_in from;
while(1)
{
char receive[256] = "";
int bytes_received = recvfrom(ServerSocket, receive, 256, 0, (sockaddr*)&from, (int *)sizeof(sockaddr_in));
if(bytes_received > 0)
{
printf("%s", receive);
char buffer[256] = "I've already gave you";
sendto(ServerSocket, buffer, strlen(buffer), 0, (sockaddr*)&from, sizeof(sockaddr_in));
}
Sleep(500);
}
}

The client is sending successfully the data becosue I don't get message: "nothing sent" but something with receiving in server code might be wrong. Nothing is being printed on client or server program... I have been trying to solve this for past 3 hours without success. Hope someone could help me!
int bytes_received = recvfrom(ClientSocket, receive, 256, 0, (sockaddr*)&from, (int *)sizeof(sockaddr_in));

wrong!


int addrlen = sizeof(sockaddr_in);
int bytes_received = recvfrom(ClientSocket, receive, 256, 0, (sockaddr*)&from, &addrlen);


Same for server.

Everything is better with Metal.

BTW, you should send strlen() + 1, not strlen, as terminating character will not be sent.

Everything is better with Metal.

Omg, such a stupid detail... int addrlen = sizeof(sockaddr_in); helped. Honestly I've got no idea why it really has to be so but the problem is solved now and it seems to support more than 1 client biggrin.png.Thanks a lot papalazaru!

edit:
Anyway, is that a good aproach to send data from server to client only after server gets data from client? Just as in my code?

Omg, such a stupid detail... int addrlen = sizeof(sockaddr_in); helped. Honestly I've got no idea why it really has to be so but the problem is solved now and it seems to support more than 1 client biggrin.png.Thanks a lot papalazaru!

edit:
Anyway, is that a good aproach to send data from server to client only after server gets data from client? Just as in my code?


That's how it's done usually (assuming LAN games).

1) Server advertises his session, using a UDP broadcast socket, and broadcasting 'I'm running a server on port xxxx' packets once in a while.
2) Client listens to server broadcasting port. That gives you the server address, and the server port.
3) client attempts to connect to the server, sending information about himself, ready to be verified by the server.
4) server accepts / reject connection request.
5) client is now connected and validated.
6) at regular intervals, clients send 'keep alive' ping packets to the server to notify him we're still connected.
7) if a client connection is idle for say, more than 30 seconds, kick the client from the game.

You can do the opposite version. Clients, when looking for a server, boradcast a 'are you there?' packet on a known port. Then the servers reply to that message, thus advertising their presence.

The connection handshake is usually performed via a simple state machine on both client and server side. It's a bit like the TCP connection establishment protocol, but it doesn't have to be that complicated.

Everything is better with Metal.

This topic is closed to new replies.

Advertisement