Jump to content

  • Log In with Google      Sign In   
  • Create Account

multiple connections in UDP server


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
12 replies to this topic

#1 savail   Members   -  Reputation: 333

Like
0Likes
Like

Posted 19 August 2012 - 11:20 AM

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!

Sponsor:

#2 SiCrane   Moderators   -  Reputation: 9598

Like
0Likes
Like

Posted 19 August 2012 - 11:51 AM

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.

#3 0BZEN   Crossbones+   -  Reputation: 2016

Like
1Likes
Like

Posted 19 August 2012 - 04:31 PM

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.


#4 savail   Members   -  Reputation: 333

Like
0Likes
Like

Posted 19 August 2012 - 04:33 PM

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

Edited by savail, 19 August 2012 - 04:41 PM.


#5 hplus0603   Moderators   -  Reputation: 5309

Like
3Likes
Like

Posted 19 August 2012 - 11:17 PM

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 };

#6 savail   Members   -  Reputation: 333

Like
0Likes
Like

Posted 20 August 2012 - 05:19 AM

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!

Edited by savail, 20 August 2012 - 05:21 AM.


#7 0BZEN   Crossbones+   -  Reputation: 2016

Like
2Likes
Like

Posted 20 August 2012 - 05:36 AM

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.

Edited by papalazaru, 20 August 2012 - 05:37 AM.

Everything is better with Metal.


#8 0BZEN   Crossbones+   -  Reputation: 2016

Like
1Likes
Like

Posted 20 August 2012 - 05:42 AM

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

Everything is better with Metal.


#9 savail   Members   -  Reputation: 333

Like
0Likes
Like

Posted 20 August 2012 - 05:46 AM

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 Posted Image.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?

Edited by savail, 20 August 2012 - 06:24 AM.


#10 0BZEN   Crossbones+   -  Reputation: 2016

Like
1Likes
Like

Posted 20 August 2012 - 07:14 AM

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 Posted Image.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.


#11 savail   Members   -  Reputation: 333

Like
0Likes
Like

Posted 20 August 2012 - 07:30 AM

Thanks a lot!

#12 0BZEN   Crossbones+   -  Reputation: 2016

Like
0Likes
Like

Posted 20 August 2012 - 04:49 PM

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 Posted Image.Thanks a lot papalazaru!


I'm surprised this hasn't blown up in your face tbh. Although the function most likely reads from the location at address sizeof(sockaddr_in), which would be 0x00000010 or there about, and not write to it, it should still throw an access violation.

In any case, always handle your errors correctly. You should call WSALastError() and this would have retuned WSAEINVAL, or invalid argument.

Edited by papalazaru, 20 August 2012 - 04:56 PM.

Everything is better with Metal.


#13 hplus0603   Moderators   -  Reputation: 5309

Like
0Likes
Like

Posted 20 August 2012 - 08:46 PM

Access errors in kernel space generally returns an error, rather than actually raise an exception.
Each system call actually first validates the reachability of all argument data areas before dispatching, and if it's a bad address, returns an error.
Btw: This makes certain system calls on Linux (such as ioctl()) very hard to implement robustly.

Anyway, to the OP saying "no idea why it really has to be so," the difference between a pointer to a value, and the value itself, is fundamental to programming in C or C++. If you don't understand the difference, then you should not yet be trying network programming.

enum Bool { True, False, FileNotFound };




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