A Simple C++/SDL_Net Chat Server & Client

Update – Nov 2011: I’ve refactored this code into something significantly easier to work with, modify and extend – so you should probably try this instead: http://r3dux.org/2011/11/a-simple-csdl_net-chat-server-client-rewritten/.

I was due to be teaching some network programming in the new term, so I thought I’d try to find the simplest library for cross-platform socket programming and knock up some examples that I could teach from. The trouble is, there are lots of different socket libraries… Lots and lots. So I did a bit of investigating and came up with the following:

Library Good Points Bad Points
Boost ASIO
  • The real deal – a world-class, well documented socket library
  • Comprehensive – you can do absolutely anything with it
  • More complicated than I’d like for the level I’m teaching at – I’m not convinced they’ll get it
  • You need to include the boost library in each project, which makes each project big (like 60MB+ big)
C++ Sockets Library
  • Lots of documentation
  • Appears to be very solid from all accounts
  • I couldn’t get it to play ball!
  • Pretty small
  • Works without you having to jump through too many hoops
  • Decent level of abstraction without the need to mess about with too much C (as opposed to C++) stuff
  • Does not require SDL – SDL_net can be happily used standalone
  • Good documentation available at:
  • You do still need to transfer strings to char array pointers
  • Resolving hosts and IPs puts the details in Network Byte Order (i.e. Big Endian) numbers, which you then have to jump through hoops to retrieve as human-readable values, so you end up doing stuff like hacking a unsigned 32-bit number into an array of four 8-bit numbers to get the dot-quad IP address etc.
NetLink Socket Library
  • Small!
  • No documentation at all (that I could find), which could be because…
  • …netlink is already the name of a *nix socket mechanism which transfers data between kernel-space and user-space – why the hell would you name your C++ socket library with a name which is already used for a different type of socket communication? Fail.
SimpleSockets (now defunct)
  • ?!?
  • Surprisingly for a library called SimpleSockets, not that simple – lots of memset and memcpy stuff needed

In the end I chose SDL_net as teh winnah, as I’d already done some SDL stuff with the class previously (before switching to GLFW to minimise code-bloat), and I managed to get SDL_net up and communicating pretty easily. So, for the next couple of days I put together some simple client/server examples, culminating in the code you’ll find below, which is a (very) simple IRC-esque chat server.

Have a look – you can tell what it’s doing from the output in the windows:

SDL_net Client-Server Example
The server is in the middle, the clients connect in, and chat commences (click for larger, more legible version)

Although I’ve written this code in Linux, as SDL_net is cross-platform, this code should be cross platform – only there are two tweaks you’ll need to make for it to work in Windows: I’ve used some custom kbhit and getch functions to check for a keypress and read what key was pressed, if one was. These functions come natively with Windows, so you should use the native versions and strip the custom ones out.

With those small changes made this should work fine in Windows – but if it doesn’t please feel free to fix it yourself and send me the changes you made :)

As the code for all this is a couple of hundred lines for each for the client and server I’ve put all the source after the jump. Part of the reason it’s so large is that I’ve commented it to the hilt (no really, I’ve gone to town on it – even by my exceptionally verbose standards) as it was originally meant to be a teaching aid. Also, I’ve also left a lot of commented-out debug code in there, so you can uncomment it if you’d like to see exactly what’s going on behind the scenes.

Anyways, I hope this is of use to someone starting off socket programming with SDL_net – and if you have any issues or such please feel free to sling a comment in the article and I’ll do my best to help out.


SDL_net Server:


The Kicker: Soon after doing all this research and spending a few days (of my own time, unpaid) writing client/server code I found out that I’m not teaching any programming this year, and have instead been assigned Systems Analysis & Design and MS/Cisco Networking. Pah! I’m not going to call this time wasted though – I learnt a lot, and I hope that you might find this code of use too.. =D

Update – Nov 2011: I’ve refactored this code into something significantly easier to work with, modify and extend – so you should probably try this instead: http://r3dux.org/2011/11/a-simple-csdl_net-chat-server-client-rewritten/.

50 thoughts on “A Simple C++/SDL_Net Chat Server & Client”

  1. The fact that this was written to teach network programming makes this code a great resource for anyone learning SLD_net. Thanks!

  2. This is absolutely terrific and helpful. I’ve been looking for exactly that kind of messenger server example and this is by far the simplest.
    Thanks alot!

  3. Just one thing which bothers me and would be great if you can help with: you state that SDL_net doesn’t require SDL, but it does so at both Compile (“Where’s SDL.h?”) & Link (“Where’s SDL.dll?) time.
    They also mention it at . So what did I not get here? Am I using a different version or what? My version of SDL_Net is 1.2.7.


    1. Hi Assaf,

      I’m not sure your comment came through the filters correctly (“they also mention it at .”??) – but at no point am I ever including SDL.h or linking to SDL.dll. SDL_Net is completely standalone from SDL as far as I’m aware. Where are you getting these “Where’s SDL.blah” statements from?

      I have no idea what version of SDL_Net I used – whichever was current at the time I wrote this post or a week or so earlier.

  4. Hi Al,

    Thanks for your reply.

    Sorry about the mess. Okay, “they also mention it at ” had the download page’s link after it, same as the one you gave in the libraries table above.
    In the 1.2.7 version (that’s where it’s currently pointing), SDL_net.h includes SDL.h.

    So, SDL_net is indeed coupled with SDL (in this version at least) , but only to utilize the SDL_Get/SetError() functions. The author also mentions that he wishes to disentangle the libraries in the future.

    So all one needs to do is to find a different solution for getting/setting errors and he can be SDL-free.


    1. Ah, I get ya. I’m not using SDL_Get/SetError functions, so that’s probably why I’m not seeing the dependency crop up.

      Cheers for the clarification :D

      Yup – you’re right. SDL_net requires the SDL library. I must’ve got my head in a twist about it.

    1. IPaddress and TCPsocket are built in types provided by the SDL_net package.

      To compile the code you’ll need to link in the SDL and SDL_net libs, as well as include SDL_net.h – which is where these new types are defined.

      For example, inside SDL_net.h, you’ll find the following code (amongst other things):

  5. if u dont mind i have another question to ask.. how can this program be multiple client chat, do we need to define the port address on client’s computer. what about the server… need to do some change or not.. hehe.. sorry. so many question to ask..i really want to know how this program work..

    1. The program comes in two parts:
      – A chat server which can link multiple clients so they can chat, and
      – A client application which can connect to the server.

      The chat flow goes like this:
      1 – Run the server, which sits there waiting for incoming connections,
      2 – Run a client, which connects to the server. The client can send messages to the server, and the server then sends those messages to all connected clients.

      So, if you first run the server and leave it running, and then run one instance of the client, then the client connects to the server and can talk to it – but there’s no-one to talk to as there are no other clients!

      If you then run ANOTHER copy of the client (while the first client is still running), then there are now two clients connected to the server, and any message entered into any client will be broadcast (by the server) to all other clients.

      You can configure the number of clients that can connect to the server before the server will refuse any more connections, I think I set that to be a low number like 4 clients connected at once, but you can change it to be any number you like.

      When the server starts it opens up port 1234 to listen on, and it can listen to multiple connections on that port. When a client starts, it connects to port 1234 on (if I remember correctly) any available, valid socket i.e. the client picks a random port to listen/transmit on – which is connected to the server port 1234, and the server keeps track of all the ports of the connected clients.

      Will post up build instructions soon – hope this helps for now.


    1. Not quite…

      The server just sits in the background and listens for incoming connections. When it gets an incoming connection from a client, it adds the client to the list of active clients. The server then takes any messages that it receives from any client, and sends the message on to all the other connected clients in the list (if there are any).

      A client just connects to the server, and allows you to type some text which gets sent to the server. When the server receives that text, as mentioned above, it sends on the message to any other connected clients.

      That’s it! =D

      Also, I might as well give you the build instructions now I have a moment. To compile both the client and the server projects you need to link in the following libraries:

      – libSDL (on my system this means the file libSDL.a, which is in the package libsdl1.2-dev)

      – libSDL_net (on my system this means the file libSDL_net.a, which is in the package libsdl1.2-net-dev)

      – pthread (on my system this means the file libpthread.so.0 which should exist as a core part of your Ubuntu system – I’d imagine it’s in /usr/lib/ but I don’t run Ubuntu anymore so can’t guarantee it).

      With that done, the project should compile without issue.

      Let me know how you get on.

  6. i already install the SDL and SDL_net lib in my UBUNTU but i dont know how to compile it.. i have try compile using compilation script on the internet but got error..

    1. You’re making life difficult for yourself by compiling from the command line – it’s far easier to set libraries and paths in an IDE like Code::Blocks or such…

      Anyways, I looked into it and (assuming you have the server and clients called SDL-Net-Server.cpp and SDL-Net-Client.cpp), you can build them with the following commands:

      Where the generated executables will be called SDL-Net-Server and SDL-Net-Client respectively. Using the -l switch uses the shared object (.so) versions of the libraries, so the final executables won’t be standalone i.e. the system running them will need to have those same libraries available on the system to execute successfully, but this is good enough for our purposes.

      I’ve even put the files together into a zip for you with “build-server.sh” and “build-client.sh” scripts to do the commands for you – all you should have to do is make the build*.sh scripts executable with chmod +x build-server.sh and chmod +x build-client.sh – or, of course, you could just copy/paste/run the above commands one at a time (making sure that the .cpp files are in the same directory where you’re running the commands!).

      You can find the archive here

      I reckon you’ll be able to do it this time!

      Final note – when compiling the client it’ll moan about an unused variable: don’t worry about it, it’s just a warning (as opposed to an error), and I think the variable it’s complaining about IS used in the program when some of the debug comments are uncommented!).


  7. thank u very much… i able to execute the file and compile.. now i have 3 file in the folder client and folder sever.. which 2 file i got from u and another 1 file exist after i follow your instruction.. is this correct..?? :) im not sure… so how to run this file..

  8. thanks again.. i don’t know how to say thank to u.. :).. can i ask something.. if i want to increase the no of client.. then how.. do i need to change the code only or need to change something in build*.sh also

    1. To increase the number of clients that can connect at once, you have to change the number of sockets available in the server at line 13:

      And then you obviously have to recompile the server.

      The server itself takes up 1 socket, so if MAX_SOCKETS is 4, you can connect 3 clients – if MAX_SOCKETS is 10, you can connect 9 clients, etc.

      You can see this at the line 14 where it says:

      To shutdown the server, you have to enter “shutdown” into one of the clients connected to the server – on receiving the “shutdown” message, the server will… shut down.

      The shutdown flag is set on line 224 to 230, finally exiting the main loop at line 239.

      It’s all there in the source code – you just need to look.

  9. then on client computer, do we need to compile the file again or we need to copy the application that already execute in my computer

    1. Any changes you make to ANY code have to be compiled/recompiled to produce the executable file (incorporating the changes) that you ‘run’.

      So if you change the server code, you have to recompile and run the new server. And if you change the client code, then you need to recompile and run the new client.

      If I understand you correctly, you just want to allow the server to accept more clients. To do this, you simply have to change the number of clients the server will accept on line 13 of the server code (as I’ve already shown you), and then recompile the server code to produce a new server executable which you can run, and then allow clients to connect to it.

      So you don’t compile the client again, but you will have to compile the server again.

      That is, UNLESS you want to run the server on one computer, and the clients on other (different) computers, in which case you’ll need to change the client source code so that lines 96 to 99 change FROM:


      Recompile the client with those changes made.

      At which point, when you run a client, you’ll be asked for the server address (i.e. IP address) of the computer which is running the server software, instead of the client assuming localhost/ as the address of the server.

  10. correct.. that was what i want to do with your program.. brilliant. ..so now let me try first.. later i will ask u again if i have some problem. i need to find my friend to compile this program in other computer..

  11. i run the client prog on other computer but got this error
    Failed to open socket to server: Couldn’t connect to remote host
    i compile this file in my comp.. so is that problem

    1. Is that after changing the client so that you have to specify the server address, and then specifying the correct IP address of server?

      There are many issues that could be going on here:
      – If the other computer and the server are not on the same network it won’t work by providing internal IPs, you’ll have to provide external IPs of the gateways to the server, and then port-forward the server port (1234) to the correct internal IP from the router…
      – Firewalls and proxies could be in the way,
      – You might not even have recompiled the client to allow for specifying an IP address for all I know..
      – Many, many other factors.

      I’m sorry, but you don’t have the technical skills to do this. I’m not even sure WHY you want to use this client/server code across networks – it’s not a fully functional chat client, it’s just an example of how to do the most basic possible client/server socket communication which I put together to teach teenagers some basic socket code.

      If you really want to run a peer-to-peer chat client (i.e. a chat client that doesn’t use a centralised server, as chat services like MS Live, YahooChat, ICQ, IRC etc DO use centralised servers), then might I suggest searching for “p2p chat client” – it’ll come up with things like:
      JabberD14 jabber (protocol) server with any jabber client of your choice.

      If you’re going to persist with using the client/server code provided, then you’ll have to find someone who can see your network and IP setup and advise from the ground – I cannot do that from here.

      Also, as mentioned, this is just example code I put together to teach from, and NOT an official, supported chat system.

      I’ve done as much as I can, and I think I’ve been very patient and answered all of your questions to the best of my ability – but now you’re on your own.

      Please do not contact me with any further questions regarding the source code – I am not a limitless fountain of free technical support. If you want to learn programming and networking, then go and learn programming and networking instead of relying on other people to solve each and every issue that you have.

      Best of luck.

  12. :) . orite.. thanks for ur reply.. i have learn a lot from u.. i will try my best to fix this thing.. thank u very much.. may god bless u..

  13. can i have your name to put in my reference together with your website address. if u don’t want to reveal your name here may be u can email me..anis152003@yahoo.com. thanks a lot ..sir/madam. actually i’m doing this for my Laboratory.. I’m university Student. I take electric telecommunication and this is my final year. Since i have only 3 week to complete this and i know nothing about socket programming and UBUNTU, so i just take your example. Hope u don’t mind

  14. I’m quite interesting to the server- multiple client program..may I know if all client simultaneously click the Enter after type the message then the server cant detect which client sent, correct??

    May I know isn’t need to allocate different port to different client?? I’m new to ubuntu and chat programming..may I know which part of the above program need to modify in order using different port for each client??

    Thanks a lot for the help…
    Just wonder if using different port the program can work @@

    1. 1 – The server CAN tell which client sent which message – it needs to know so that it can broadcast the message to all the other clients. You can even see in the server output that it says “Received [some message] from client [some client number]”.

      2 – Each client already has its own (unique) randomly assigned port. To see which ports the client(s) are using, try using the command:

      This will find all tcp sockets which are currently open on the machine, and the “1234” bit is the default port number of the server.

      If you want to assign specific ports to clients, then you’ll have to look up how to do that in the SDL_net documentation.

      Best of luck.

  15. Sir, i have try this program using LAN and the program work great.. We can communicate with each other. but i have something to adjust. for this program, at client side we wouldn’t know the message is sent by which client. If we have multiple client, we are going to have a little bit problem to detect which client sent the message.Only the server know who is sending the message. But never mind. I will configure it out and will let you know the progress. Thanks a lot Sir/Teacher

    1. Easiest way to do this is to modify the client to ask for a username (i.e. who is using the client) and then just prepend that username to each message sent from the client.

  16. hi Sir, after looking at some example of C++ and socket programming, i already successful modify the client code to ask for user name and broadcast it together with the message.. The received message will be like this

    Received: My message :User Name /Client Name

    That is the best that i can do.. :)

    Thanks for the clue.. i really appreciate it..

  17. this code was so well designed that i added sdl to it and made it a regular, non terminal code with minimal effort. I hope you do get teaching gigs cuz you are a good example.

  18. Thank you so much for this tutorial! I am in the process of creating a multiplayer game. This tutorial was exactly what I needed to get used to SDL_net and get chat working. Once again, thanks!


  19. This is a synchronous socket system right?
    Is there any way to create an asynchronous socket with SDL_net?
    Or at least a non-blocking send and receive function?

    Nice tut by the way.

  20. Thanks a lot! Very useful tutorial! You are gr8 m8 :D
    You just saved me a lot of pain i had since few days! Now everything is clear – i just lacked this “int serverSocketActivity = SDLNet_SocketReady(serverSocket);”
    this one line of code gave me what I needed ^_^ – I thought i read the documentation thoroughly but somehow missed this function :)

    1. Yeah, I reckon so… the SDL_net send and receive methods accept void pointers instead of specifically requiring char arrays, so I don’t see why not.

      If you do the refactoring and it all works, it’d be great if you posted the code and I’ll post it here and credit you. You can, of course, do anything with the code, so you don’t have to pass on any refactoring work you do if you don’t want to. Also, you might like to work from the re-factored version of the code here rather than this version.

Leave a Reply

Your email address will not be published.