• 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
John Schultz

UDP Client Server Echo Example

7 posts in this topic

Here's an example UDP echo server I created from a simple UDP example (originally to help another thread question, now solved). Additionally, it shows how to use select() to poll the socket (with an optional time out). Compiled and tested on and between Win32/Cygwin and Linux (would need to be modified for Win32/Winsock). Compile: gcc -Wall -o client udpClient.c gcc -Wall -o server udpServer.c Run: ./server& ./client 127.0.0.1 this is a test. (or run server in another console, separate machines, etc.). Client:
/* fpont 12/99 */
/* pont.net    */
/* udpClient.c */

/* Converted to echo client/server with select() (timeout option) */
/* 3/30/05 John Schultz */

#include <stdlib.h> /* for exit() */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h> /* memset() */
#include <sys/time.h> /* select() */ 

#define REMOTE_SERVER_PORT 1500
#define MAX_MSG 100

/* BEGIN jcs 3/30/05 */

#define SOCKET_ERROR -1

int isReadable(int sd,int * error,int timeOut) { // milliseconds
  fd_set socketReadSet;
  FD_ZERO(&socketReadSet);
  FD_SET(sd,&socketReadSet);
  struct timeval tv;
  if (timeOut) {
    tv.tv_sec  = timeOut / 1000;
    tv.tv_usec = (timeOut % 1000) * 1000;
  } else {
    tv.tv_sec  = 0;
    tv.tv_usec = 0;
  } // if
  if (select(sd+1,&socketReadSet,0,0,&tv) == SOCKET_ERROR) {
    *error = 1;
    return 0;
  } // if
  *error = 0;
  return FD_ISSET(sd,&socketReadSet) != 0;
} /* isReadable */

/* END jcs 3/30/05 */

int main(int argc, char *argv[]) {
  
  int sd, rc, i, n, echoLen, flags, error, timeOut;
  struct sockaddr_in cliAddr, remoteServAddr, echoServAddr;
  struct hostent *h;
  char msg[MAX_MSG];


  /* check command line args */
  if(argc<3) {
    printf("usage : %s <server> <data1> ... <dataN> \n", argv[0]);
    exit(1);
  }

  /* get server IP address (no check if input is IP address or DNS name */
  h = gethostbyname(argv[1]);
  if(h==NULL) {
    printf("%s: unknown host '%s' \n", argv[0], argv[1]);
    exit(1);
  }

  printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name,
	 inet_ntoa(*(struct in_addr *)h->h_addr_list[0]));

  remoteServAddr.sin_family = h->h_addrtype;
  memcpy((char *) &remoteServAddr.sin_addr.s_addr, 
	 h->h_addr_list[0], h->h_length);
  remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT);

  /* socket creation */
  sd = socket(AF_INET,SOCK_DGRAM,0);
  if(sd<0) {
    printf("%s: cannot open socket \n",argv[0]);
    exit(1);
  }
  
  /* bind any port */
  cliAddr.sin_family = AF_INET;
  cliAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  cliAddr.sin_port = htons(0);
  
  rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr));
  if(rc<0) {
    printf("%s: cannot bind port\n", argv[0]);
    exit(1);
  }

/* BEGIN jcs 3/30/05 */

  flags = 0;

  timeOut = 100; // ms

/* END jcs 3/30/05 */

  /* send data */
  for(i=2;i<argc;i++) {
    rc = sendto(sd, argv[i], strlen(argv[i])+1, flags, 
		(struct sockaddr *) &remoteServAddr, 
		sizeof(remoteServAddr));

    if(rc<0) {
      printf("%s: cannot send data %d \n",argv[0],i-1);
      close(sd);
      exit(1);
    }

/* BEGIN jcs 3/30/05 */

    /* init buffer */
    memset(msg,0x0,MAX_MSG);

    while (!isReadable(sd,&error,timeOut)) printf(".");
    printf("\n");

    /* receive echoed message */
    echoLen = sizeof(echoServAddr);
    n = recvfrom(sd, msg, MAX_MSG, flags,
      (struct sockaddr *) &echoServAddr, &echoLen);

    if(n<0) {
      printf("%s: cannot receive data \n",argv[0]);
      continue;
    }

    /* print received message */
    printf("%s: echo from %s:UDP%u : %s \n", 
      argv[0],inet_ntoa(echoServAddr.sin_addr),
      ntohs(echoServAddr.sin_port),msg);

/* END jcs 3/30/05 */

  }
  
  return 1;

}




Server:
/* fpont 12/99 */
/* pont.net    */
/* udpServer.c */

/* Converted to echo client/server with select() (timeout option). See udpClient.c */
/* 3/30/05 John Schultz */

#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <stdio.h>
#include <unistd.h> /* close() */
#include <string.h> /* memset() */

#define LOCAL_SERVER_PORT 1500
#define MAX_MSG 100

int main(int argc, char *argv[]) {
  
  int sd, rc, n, cliLen, flags;
  struct sockaddr_in cliAddr, servAddr;
  char msg[MAX_MSG];

  /* socket creation */
  sd=socket(AF_INET, SOCK_DGRAM, 0);
  if(sd<0) {
    printf("%s: cannot open socket \n",argv[0]);
    exit(1);
  }

  /* bind local server port */
  servAddr.sin_family = AF_INET;
  servAddr.sin_addr.s_addr = htonl(INADDR_ANY);
  servAddr.sin_port = htons(LOCAL_SERVER_PORT);
  rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
  if(rc<0) {
    printf("%s: cannot bind port number %d \n", 
	   argv[0], LOCAL_SERVER_PORT);
    exit(1);
  }

  printf("%s: waiting for data on port UDP %u\n", 
	   argv[0],LOCAL_SERVER_PORT);

/* BEGIN jcs 3/30/05 */

  flags = 0;

/* END jcs 3/30/05 */

  /* server infinite loop */
  while(1) {
    
    /* init buffer */
    memset(msg,0x0,MAX_MSG);

    /* receive message */
    cliLen = sizeof(cliAddr);
    n = recvfrom(sd, msg, MAX_MSG, flags,
		 (struct sockaddr *) &cliAddr, &cliLen);

    if(n<0) {
      printf("%s: cannot receive data \n",argv[0]);
      continue;
    }
      
    /* print received message */
    printf("%s: from %s:UDP%u : %s \n", 
	   argv[0],inet_ntoa(cliAddr.sin_addr),
	   ntohs(cliAddr.sin_port),msg);

/* BEGIN jcs 3/30/05 */

    sleep(1);
    sendto(sd,msg,n,flags,(struct sockaddr *)&cliAddr,cliLen);

/* END jcs 3/30/05 */
    
  }/* end of server infinite loop */

return 0;

}



[Edited by - John Schultz on March 31, 2005 3:13:44 PM]
0

Share this post


Link to post
Share on other sites
Thanks for sharing!

However, the headers of that code appear to credit "Frederic Pont" from www.pont.net, not John Schultz. Looking at that web site, it's un-clear to me what part of this that _you_ created.

Remember that mis-representation of copyright is a federal crime, and is not something you should be doing, even in a friendly forum such as this.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by hplus0603
Thanks for sharing!

However, the headers of that code appear to credit "Frederic Pont" from www.pont.net, not John Schultz. Looking at that web site, it's un-clear to me what part of this that _you_ created.

Remember that mis-representation of copyright is a federal crime, and is not something you should be doing, even in a friendly forum such as this.


Check his own /*comments*/ underneath those original comments.
0

Share this post


Link to post
Share on other sites
Quote:
Original post by hplus0603
Thanks for sharing!

However, the headers of that code appear to credit "Frederic Pont" from www.pont.net, not John Schultz. Looking at that web site, it's un-clear to me what part of this that _you_ created.

Remember that mis-representation of copyright is a federal crime, and is not something you should be doing, even in a friendly forum such as this.


Perhaps you are thinking about another post? There are no headers here (two source files). It appeared the changes I made would be clear based on the comments I added to the code (conversion of simple UDP client/server to an echo client server); the code is very short/trivial.

I have edited the original post and added additional comments around the code I changed/added.

What lead you to believe there was a violation of US Copyright law?
0

Share this post


Link to post
Share on other sites
Quote:
Here's an example UDP echo server I created


When I read this, it sounded to me like you claimed authorship. I like the edits, and, again, thanks for sharing!
0

Share this post


Link to post
Share on other sites
Quote:
Original post by hplus0603
Quote:
Here's an example UDP echo server I created


When I read this, it sounded to me like you claimed authorship. I like the edits, and, again, thanks for sharing!


No problem! Hopefully this code will be useful for those just starting out or needing to test basic UDP functionality.

I am sensitive to copyright law as my own code (licensed to another companies) has been misrepresented in the past (my name removed from the copyright line and another's substituted). An example of a Virtual Reality headset SDK I wrote in 1994 here. It appears my name has been completely removed, except for my initials in the serial bi-modal assembly file. The company went out of business years ago.
0

Share this post


Link to post
Share on other sites
[Note: moved this to it's own thread for ease of reading]

I just tried a modified version of this code for a class project I'm doing where I keep sending out packets, and then instead of a while, I used an if on the isReadable (my version) and then if isReadable == 1 then I would recvfrom the data. I did this and I my data was somewhat corrupted as opposed to simply doing a sendto and then blocking with a recvfrom. Any ideas (I'm checking the actual bytes and they are different btw).

Here's my function, thanks in advance if you guys have any ideas. I'm stumped.

// isReadable
// Checks to see if the Socket has something to be read
int isReadable( int sockfd, int usec ) {
fd_set socketReadSet;
FD_ZERO(&socketReadSet);
FD_SET(sockfd, &socketReadSet);

// Setup timeout
struct timeval tv;
if( usec ) {
tv.tv_sec = usec / 1000000;
tv.tv_usec = (usec % 1000000);
} else {
tv.tv_sec = 0;
tv.tv_usec = 0;
} // end if



// Select on our Socket Description
if( select(sockfd+1,&socketReadSet,0,0,&tv) == -1 ) {
perror("select");
exit(1);
}

return FD_ISSET(sockfd,&socketReadSet) != 0;

} // end isReadable


[Edited by - Hexxagonal on April 13, 2005 12:43:36 PM]
0

Share this post


Link to post
Share on other sites
Hi,

select() will not have any effect on data received with recvfrom(). If your isReadable() was somehow broken (it looks OK), worst case is you'd see old data as new data was not present (if the socket was set to non-blocking and you were not checking for errors returned by recvfrom()), or you would block waiting for data to actually arrive (blocking socket).

Make sure you are error checking recvfrom(), and also look at how your read buffer is handled (on stack, class member, global, etc.).
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