r3dux.org

A number-pimping side project from the valleys in *NEW* upside-down flavour.

  • Home
  • ABOUT
  • OLD SITE
  • SEARCH
  • FEEDBACK

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

r3dux | November 25, 2011

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// Re-written simple SDL_net socket server example | Nov 2011 | r3dux
// Library dependencies: libSDL, libSDL_net
 
#include <iostream>
#include <string>
#include <SDL/SDL_net.h>
#include "ServerSocket.h"
 
int main(int argc, char *argv[])
{
	// Initialise SDL_net
	if (SDLNet_Init() == -1)
	{
		std::cerr << "Failed to intialise SDL_net: " << SDLNet_GetError() << std::endl;
		exit(-1);
	}
 
	// Create a pointer to a ServerSocket object
	ServerSocket *ss;
 
	try
	{
		// Try to instantiate the server socket
		// Parameters: port number, buffer size (i.e. max message size), max sockets
		ss = new ServerSocket(1234, 512, 3);
	}
	catch (SocketException e)
	{
		std::cerr << "Something went wrong creating a SocketServer object." << std::endl;
		std::cerr << "Error is: " << e.what()   << std::endl;
		std::cerr << "Terminating application." << std::endl;
		exit(-1);
	}
 
	try
	{
		// Specify which client is active, -1 means "no client is active"
		int activeClient = -1;
 
		// Main loop...
		do
		{
			// Check for any incoming connections to the server socket
			ss->checkForConnections();
 
			// At least once, but as many times as necessary to process all active clients...
			do
			{
				// ...get the client number of any clients with unprocessed activity (returns -1 if none)
				activeClient = ss->checkForActivity();
 
				// If there's a client with unprocessed activity...
				if (activeClient != -1)
				{
					// ...then process that client!
					ss->dealWithActivity(activeClient);
				}
 
			// When there are no more clients with activity to process, continue...
			} while (activeClient != -1);
 
		// ...until we've been asked to shut down.
		} while (ss->getShutdownStatus() == false);
 
	}
	catch (SocketException e)
	{
		cerr << "Caught an exception in the main loop..." << endl;
		cerr << e.what() << endl;
		cerr << "Terminating application." << endl;
	}
 
	// Shutdown SDLNet - our ServerSocket will clean up after itself on destruction
	SDLNet_Quit();
 
	return 0;
}

Socket Client

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// Re-written simple SDL_net socket client example | Nov 2011 | r3dux
// Library dependencies: libSDL, libSDL_net
 
#include <iostream>
#include <string>
#include <SDL/SDL_net.h>
 
#include "ClientSocket.h"
 
int main(int argc, char *argv[])
{
	// Initialise SDL_net (Note: We don't initialise or use normal SDL at all - only the SDL_net library!)
	if (SDLNet_Init() == -1)
	{
		std::cerr << "Failed to intialise SDL_net: " << SDLNet_GetError() << std::endl;
		exit(-1);
	}
 
	// Create a pointer to a ServerSocket object
	ClientSocket *cs;
 
	try
	{
		// Try to instantiate the client socket
		// Parameters: server address, port number, buffer size (i.e. max message size)
		// Note: You can provide the serverURL as a dot-quad ("1.2.3.4") or a hostname ("server.foo.com")
		cs = new ClientSocket("127.0.0.1", 1234, 512);
	}
	catch (SocketException e)
	{
		std::cerr << "Something went wrong creating a ClientSocket object." << std::endl;
		std::cerr << "Error is: " << e.what()   << std::endl;
		std::cerr << "Terminating application." << std::endl;
		exit(-1);
	}
 
	try
	{
		// Attempt to connect to the server at the provided address and port
		cs->connectToServer();
 
		string receivedMessage = "";
 
		cout << "Use /quit to disconnect or /shutdown to shutdown the server." << endl;
 
		// Display the initial prompt
		cs->displayPrompt();
 
		// Run the main loop...
		do
		{
			// Check if we've received a message
			receivedMessage = cs->checkForIncomingMessages();
 
			// If so then...
			if (receivedMessage != "")
			{
				// Display the message and then blank it...
				cs->displayMessage(receivedMessage);
 
				// ...and then re-display the prompt along with any typed-but-not-yet-sent input
				cs->displayPrompt();
			}
 
			// Get and deal with input from the user in a non-blocking manner
			cs->getUserInput();
 
		// ... until we decide to quit or the server is shut down
		} while ( (cs->getShutdownStatus() == false));
 
	}
	catch (SocketException e)
	{
		cerr << "Caught an exception in the main loop..." << endl;
		cerr << e.what() << endl;
		cerr << "Terminating application." << endl;
	}
 
	// Shutdown SDLNet - our ClientSocket will clean up after itself on destruction
	SDLNet_Quit();
 
	return 0;
}

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

  • Linux Client and Server Code (Code::Blocks projects, libs not included)
  • Windows Client and Server Code (Visual Studio 2008 projects, libs included)

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!

Related posts:

  1. A Simple C++/SDL_Net Chat Server & Client
  2. How To: Set up a FTP Server in Linux
  3. Simple texture loading with DevIL revisited
  4. How To: Create a Simple Fireworks Effect in OpenGL and SDL
  5. How-To: Get valid integer input in C++ (a stupidly long solution to a stupidly simple problem)
Categories
Coding
Tags
C++, Client, networking, SDL_net, Server, Socket
Comments rss
Comments rss
Trackback
Trackback
Print This Post Print This Post

« San Cisco – Awkward Best AI Class Quiz Evah! »

17 Responses to “A simple C++/SDL_net chat server & client rewritten”

  1. A Simple C++/SDL_Net Chat Server & Client | r3dux.org says:
    November 25, 2011 at 5:34 pm

    [...] 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/. [...]

    Reply
  2. Su says:
    November 25, 2011 at 8:19 pm

    i just come to visit u but i’ve found a new program.. much simpler than the one u did in January..awesome.. :)

    Reply
    • r3dux says:
      November 25, 2011 at 10:16 pm

      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…

      Reply
  3. shetboy says:
    November 25, 2011 at 8:59 pm

    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 :)

    Reply
    • r3dux says:
      November 25, 2011 at 10:19 pm

      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

      Reply
      • shetboy says:
        November 26, 2011 at 12:48 am

        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.

        Reply
  4. Su says:
    November 27, 2011 at 1:36 am

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

    Reply
  5. reilly davis says:
    February 24, 2012 at 5:04 pm

    wow nice work there al

    Reply
    • r3dux says:
      February 24, 2012 at 5:16 pm

      Cheers, Reilly :D

      Reply
  6. FOX51 says:
    February 27, 2012 at 1:12 pm

    Nice work man, really good job, only one thing, can you put the windows download link corrected? and thanks for sharing

    Reply
    • r3dux says:
      February 27, 2012 at 9:22 pm

      Oops! My bad – fixed!

      Glad you like =D

      Reply
  7. alexoffspring says:
    April 21, 2012 at 2:27 am

    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

    Reply
    • r3dux says:
      April 22, 2012 at 4:15 pm

      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.

      Reply
      • alexoffspring says:
        April 24, 2012 at 10:48 pm

        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.

        Reply
  8. nate says:
    May 27, 2012 at 1:00 am

    error is : cannot bind to local port…please help

    Reply
    • r3dux says:
      May 27, 2012 at 9:43 am

      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:

      ss = new ServerSocket(2012, 512, 3);

      Client code change:

      cs = new ClientSocket("127.0.0.1", 2012, 512);

      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.

      Reply
  9. Howard says:
    July 28, 2012 at 5:57 am

    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

    Reply

Leave a Reply

Click here to cancel reply.

Translate

Categories

Archives

Tags

3D ActionScript ActionScript 3.0 Adobe AI Ballarat Bash C++ Class Convert CS4 Effect Error Film Flash FPS GLFW Glitch GLSL Hack How-To install Java Kinect Linux Live Mash-Up Microsoft Motion mount OpenGL Particle Problem PS3 Remix Retro script Slides Sound Ubuntu Video VirtualBox Wii Windows XBox

Gamercard

OpenR3dux

Misc.

Flattr this

RSS Feed

r3dux twitter feed



“Everything comes to he who waits, but it's usually cold by the time it arrives.”

rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox