A simple C++/SDL_net chat server & client rewritten

Back in January this year I was due to be teaching some diploma level programming (roughly equivalent to the UK A/S level for any Brits), and part of that had to deal with network programming with sockets and stuff, so I duly did my research and put together a simple chat server and client in SDL_net. And then my classes changed and I got moved on to teach other stuff. I wasn’t too upset though – I’d learnt a lot, and I’d put up the code to help people out who might be in a similar situation, so it was all good.

But now in November I’m back on programming duty, so I dug up my code, looked it over, and thought Naah – I can’t use that, it’s unweildy, and complex, and it would be a real pain to try to re-use the code. So I’ve gone back to the drawing board and refactored it all into something I hope is a lot more palletable and both easy to use and re-purpose. In effect, I’ve refactored it into two wrappers which now consist of a ServerSocket class and a ClientSocket class.

Check it out…

Cross Platform Socket Server and Clients
Cross platform socket connectivity? That'll be a yes, then...

Socket Server

The old chat server was 250 lines, it’s now down to 77:

Socket Client

And the old chat client was 313 lines, which is now down to 83:

On top of all this we have try/catch exception handling, a nice encapsulated & easy to work-with/modify/extend design and debug flags to control whether the client/server should be verbose or run silently. Obviously the chat client itself can’t run completely silently – you wouldn’t be able to read the messages being sent back and forth! – but when debug is off it only ever outputs anything when it receives a message or when the user enters messages to send, so it’s pretty darn quiet.

Oh, and it now comes in Linux and Windows flavours =D

Overall I’m really happy with it – it’s taken a few days to properly redesign and test (not to mention the issues involved with porting to Windows) – but I think the next time I need to do some socket stuff with C++ I’d be able to grab this code, make whatever modifications I need and get something up and running in no time.

Awthome! =P

Download links

Notes on Building for Windows

The windows client and server projects have some important tweaks made for them to compile, and it’s worth mentioning what they are:

  • The solution (which contains two projects) comes comes with a copy of the SDL and SDL_net libs and headers all merged together in the SDL folder (well, there are separate libs and include folders, but all the headers from both are in the include folder and all the libs from both are in the libs folder).
  • Each project has the following libraries linked in: SDL.lib, SDLmain.lib and SDL_net.lib, these libraries point to…
  • SDL.dll and SDL_net.dll which are in the solution’s Debug folder, so you can compile and build from Visual Studio, BUT you’lll need to copy these two dll files into the same folder as the SocketServer-Rewritten.exe or SocketClient-Rewritten.exe folders to run the executables “standalone” in other locations as opposed to build-and-run-from-visual-studio style!
  • The projects are defined as console applications, and because SDLmain.lib defines the main function as int main(int argc, char *argv[]) and not just int main() you MUST keep the definition of main in-line with the SDLmain.lib definition.
  • Finally, the projects will only build successfully in debug mode. Why? I’ve no idea. If you know how to fix it then go for it!

37 thoughts on “A simple C++/SDL_net chat server & client rewritten”

    1. Glad ya like :D

      I did as much as I could to help you out with your specific requirements within the time I had available – I wish I’d have had this ready when it would have been of use to you, but such is life…

  1. That is really nice code, great job. It would fly through one of my code reviews without a single WTF!

    Clear and simple design
    Nice comments
    Exception handling

    ‘Nuff said :)

    1. Hehe – I love that comic =D

      Thanks for your kind comments – I worked really hard on it (did you know you can’t define structs in headers? I didn’t!). Just hope it makes socket programming more do-able for my students, and maybe anyone else trying to knock together some socket stuff!

      Really, the socket server has gone up from 250 to around 500 lines, and the client from 313 to around 600 lines. But I guess the payback comes when you can use it to actually do something useful in less than 100 lines of code, and modify and extend it with ease now that the mains are now almost purely “business logic”.

      Really happy with it =D

      1. Yes, absolutely.

        The term I believe you are scratching for is loosely coupled code.

        It takes longer to design and write code adhering to these principles, but the benefits are massive time savings down the line in the current project and/or future projects.

  2. for this time the coding is a bit different and weird( for me) because the ss and cs :D but the function is the same with the previous one. what type of coding u use to make it very simple..

    you are so nice sir.. however i’ve finish my presentation and of course using your code…the presentation went smoothly.. :) thanks a lot.. i will visit u more often to learn about coding and will never forget what u have teach me… i will remember u always..

  3. Nice job.
    I downloaded it and i’m actually enjoying ‘customizing’ it :)

    I have some problems when using BACKSPACE. Any idea for solving it?

    Tnx
    alex

    1. Hmm, you’ll prolly need to look for the ASCII code for backspace (8) in the getUserInput function and remove the last character from the message when you detect it.

      There’s also the issue of moving the text carat back one character, which you could get around by re-displaying the prompt each time, but that’s not very elegant. It’s all do-able, it just might be a little fiddly to nail it with a nice cross-platform solution.

      1. Tnx for the answer. Or probably storing temporarily the input using a simple scanf can be a nice solution.

        I was wondering if SDL can be used to create a socket to a client passing through a proxy. I did not find any documentation about it yet.

    1. You need the server to be running before you can connect with a client, so I assume you mean you’re getting the error “cannot bind to local port” when running the server.

      This could possibly be because something else is already running on port 1234, so try changing the port to something else, like 2012. For example:

      Server code change:

      Client code change:

      Then, when you run the client (which you’ll need to do “standalone” if you’ve just run the server through Visual Studio [i.e. you’ll need to launch the client exe from windows explorer or the command line]) make sure you have the SDL.dll and SDL_net.dll files copied into the same location as the client executable, as it says in the Notes on building for WIndows section.

      Also, it just occurs to me that your firewall could, potentially, be blocking applications from opening ports, so you might want to try temporarily disabling it and trying again if the above doesn’t solve your problem.

      Hope this helps.

  4. Came across your revamped work while looking for serverless, P2P sample code – if you ever get motivated, or have to teach on this subject again, that would be a nice addition. – thank you for publishing your code. – Howard in Florida

  5. I have been looking for something like this for a couple of days and finally came across this. Thank you!
    I’m running openSUSE and managed to compile your older version with the information you gave Su here:

    http://r3dux.org/2011/01/a-simple-sdl_net-chat-server-client/#comment-7058

    I am relatively new to linux and could use some guidance on how to compile this version of your chat server.

    I tried: g++ -Wall sdl-config --cflags --libs -lpthread -lSDL -lSDL_net -o Server ./ServerSocket.cpp

    but these errors popped up:

    /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libpthread.so when searching for -lpthread
    /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libpthread.so when searching for -lpthread
    /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libSDL_net.so when searching for -lSDL_net
    /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libm.so when searching for -lm
    /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libc.so when searching for -lc
    /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../lib64/crt1.o: In function _start':
    /home/abuild/rpmbuild/BUILD/glibc-2.17/csu/../sysdeps/x86_64/start.S:119: undefined reference to
    main’
    collect2: error: ld returned 1 exit status

    Is this a 64bit related error or am I just compiling it all wrong?

    1. These errors arise if i replace ServerSocket with Main:

      /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libpthread.so when searching for -lpthread
      /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libpthread.so when searching for -lpthread
      /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libSDL_net.so when searching for -lSDL_net
      /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libm.so when searching for -lm
      /usr/lib64/gcc/x86_64-suse-linux/4.7/../../../../x86_64-suse-linux/bin/ld: skipping incompatible /usr/lib/libc.so when searching for -lc
      /tmp/cc7HBV9E.o: In function main':
      Main.cpp:(.text+0x7c): undefined reference to
      ServerSocket::ServerSocket(unsigned int, unsigned int, unsigned int)’
      Main.cpp:(.text+0x93): undefined reference to ServerSocket::checkForConnections()'
      Main.cpp:(.text+0x9f): undefined reference to
      ServerSocket::checkForActivity()’
      Main.cpp:(.text+0xb9): undefined reference to ServerSocket::dealWithActivity(unsigned int)'
      Main.cpp:(.text+0xd0): undefined reference to
      ServerSocket::getShutdownStatus()’
      collect2: error: ld returned 1 exit status

      1. You definitely need to compile the Main.cp, for any given project, but maybe you also need to tell g++ about ServerSocket.cpp.

        Okay, looking things up gives:

        I don’t know if specifying the current directory with -I. will override the default /usr/lib/include folder for include files, if so you might need to have multiple -I switches.

        If there’s still “skipping incompatible” messages it seems to be a 32-bit/64-bit issue – so you might have the 32-bit version of some lib and the 64-bit version of another and you can’t mix and match – my Linux is 64-bit and I haven’t come across this issue.

        I’d still recommend you use an IDE rather than compile from the command line though, it’ll save you a ton of exactly this sort of grief! Get the Linux version of the project linked at the bottom of the post, install Code::Blocks, open the project and look under Project Properties | Build Options then check in the Linker settings tab look at the generic config (above Debug and Release in the top left corner) to see the list of libraries we’re linking against. Pick which libraries and locations through this and with any luck it’ll work.

        Cheers!

        1. I tried to get codeblocks working on the 64bit os but ran into issues. So I downloaded the 32bit version of openSUSE and all works perfect now :) Thanks!

          Only issue I’m trying to resolve now is the server doesn’t display anything after i run it. It still receives and sends everything and shuts down but doesn’t list anything. Any ideas?

          1. Glad you got it working =D

            The ServerSocket is likely displaying nothing because the debug flag is set to false – just go into the ServerSocket.cpp file and flip it to true on line 11 then rebuild, the server should then spit out plenty of debug info about what data it’s transmitting and to which clients.

  6. Hey long time no talk! Reviewing somethings and trying to get the windows client to connect to the linux server that I’m running in virtualbox. How did you manage to do that?

    1. Hola =D I used the bridged adaptor setting on the virtual machine’s network adapter so that the vm was on the same subnet as the physical machine – once that’s done, they’ll just talk!

      Wrote a thing about it a long while ago, but all you need is the very 1st paragraph of this: http://r3dux.org/2009/09/how-to-make-virtualbox-use-your-routers-dhcp-to-get-an-ip-address-in-linux/.

      Works on any VirtualBox running platform, not just Linux (so article title is misleading – original method only worked on Linux).

      1. I thought that I just couldn’t get that to work. I tried it both on vmware workstation and virtualbox. After I change the settings to bridged network and update the ip with the one I found with ipconfig. I notice a change that the client gets to
        “Connection okay, about to read connection status from server.”
        before it closes. That actually only happens when I forward the same port I am using for the server. Without that port forwarding client just closes. Sometimes hangs when I experiment with ips saying that it couldn’t resolve hostname but will try because it technically has a valid ip.

        I am using the visual studio 8 express edition but both client and server work fine on windows alone so I don’t think that is the issue.

        1. So I did some testing. I am able to connect a linux client to a win server. However I can’t seem to do the opposite.

          it says ” Failed to resolve the server IP to hostname:
          Attempting to continue as we have a valid IP address…”

          I know this is an old topic and hate to be a pain but could you test linux server, win client just to see if I need to make additional changes to get this working.
          Appreciate the help.

            1. Going from a Linux server to Windows clients works fine for me – you just have to tell the clients the actual IP address of the server (not 127.0.0.1):

              No idea why it’s not working for you, sorry…

              1. That is great news actually. It must be something with my router or network settings. I really appreciate you taking the time to test it out for me. I’ll try and figure it out. Cheers.

                1. Got it working. Silly me didn’t think to configure the firewall on openSUSE and allow the client to connect.

                  Now that I have that out of the way. Would it be difficult to make the client into a windows form instead of console?

    1. Good point. Shouldn’t limit myself, had no idea there were so many other options. Qt seems to offer everything I want so I’m going to give that a shot. I’ll watch some tuts tonight and see if I can implement it. Seems pretty straight forward and reminds me of my VB6 days so should be good. Thanks for the recommendation! Cheers.

  7. I’ve used your SDL networking tutorials to get my head around network programming for the first time. They have been incredibly helpful, I’ve based my code on your framework and extended it to use user commands and I’ve tested having other people connect over the internet and exchange messages. I’m currently adapting it to send data for a game project I am working on for a university class. We’re making a 3D dungeon crawler game similar to the like of Diablo, Torchlight etc. I’ll update you on the progress of my project. :)

    Your tutorials were great though, thanks for that! I might even write up one myself for my own site.

Leave a Reply

Your email address will not be published.