• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
savail

multiple connections in UDP server

12 posts in this topic

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):
[CODE]
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;
}
[/CODE]

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!
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites
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.
1

Share this post


Link to post
Share on other sites
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?

[quote name='SiCrane' timestamp='1345398670' post='4971162']
If you don't bind the socket, the system should automatically assign a unique port to each socket.
[/quote]
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
0

Share this post


Link to post
Share on other sites
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:
[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);
}
}
[/CODE]
and here's server's code:
[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);
}
}
[/CODE]
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
0

Share this post


Link to post
Share on other sites
[CODE]int bytes_received = recvfrom(ClientSocket, receive, 256, 0, (sockaddr*)&from, (int *)sizeof(sockaddr_in));[/CODE]

wrong!

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

Same for server. Edited by papalazaru
2

Share this post


Link to post
Share on other sites
BTW, you should send strlen() + 1, not strlen, as terminating character will not be sent.
1

Share this post


Link to post
Share on other sites
Omg, such a stupid detail... [CODE]int addrlen = sizeof(sockaddr_in);[/CODE] 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 [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img].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
0

Share this post


Link to post
Share on other sites
[quote name='savail' timestamp='1345463167' post='4971435']
Omg, such a stupid detail... [CODE]int addrlen = sizeof(sockaddr_in);[/CODE] 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 [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img].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?
[/quote]

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.
1

Share this post


Link to post
Share on other sites
[quote name='savail' timestamp='1345463167' post='4971435']
Omg, such a stupid detail... [CODE]int addrlen = sizeof(sockaddr_in);[/CODE] 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 [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img].Thanks a lot papalazaru!
[/quote]

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
0

Share this post


Link to post
Share on other sites
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.
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0