QuickSock: A simple UDP socket module (GLFW / C++)

Monkey Programming Forums/User Modules/QuickSock: A simple UDP socket module (GLFW / C++)

ImmutableOctet(SKNG)(Posted 2013) [#1]
Major Project Updates:

* (V1.1):
Besides some bug fixes, slightly better performance, and the ability to compile for other desktop platforms; this version is pretty much the same as V1.0 for Monkey users. The only noticeable difference while programming in Monkey is that "IsServer" is now a method, instead of a field.

You can find a full list of updates for the C++ version here: Source Forge

Here's where you can find the Monkey module(Downloads page): Source Forge - Just extract the zip to your modules folder, and that's it!

QuickSock is also available for free to C++ developers(Available for Windows, Mac, Linux, etc): Source Forge

QuickSock currently supports: STDCPP(Only tested on Windows) & GLFW(Windows, Mac, and Linux). And from what I've tested, Visual C++ 2010 and MinGW/GCC should work without any problems.

Module Description:
QuickSock is a simple project I've been working on for a little while now. It's completely open source, so edit it and redistribute it as you like. Credit for the original work would be appreciated, but it's not a requirement.

My main goal with QuickSock is to allow you to get sockets running, without having to do all the work setting them up. Right now, QuickSock exists as a simplistic layer between WinSock/BSD-Sockets, and the programmer.

Extra Information:
I wrote QuickSock in C++, and since I've never really tried to work realistically with it, I encourage you to tell me your thoughts on the C++ side of things. I'd like to make this as clean and compact as possible.

TODO List:
* Reliable packets(C++ or Monkey)
* Stream support(Monkey and/or C++)
* Asynchronous Sockets(Monkey or C++)
* TCP Sockets(C++)
/ Better error checking(C++)
X Support for other platforms(C++)
If you find any bugs while using QuickSock, please report them.

ImmutableOctet(SKNG)(Posted 2013) [#2]
{UPDATE, V1.1(April, 2013)}: QuickSock now supports BSD-Sockets, so it should be able to run on Mac OS-X and Linux.

I haven't tested it on Mac OS-X, so I'd really appreciate it if you could tell me if it at least compiles on OS-X. I have tested QuickSock on Linux both normally, and with Monkey, and everything seems to work.

ImmutableOctet(SKNG)(Posted 2013) [#3]
{SMALL-UPDATE, V1.1.1(April, 2013)}: I've tested QuickSock on Mac OS-X via XCode, and with a few tweaks I got everything running.

Anyone who wants to run QuickSock on Mac OS-X via Monkey should download the V1.1.2 Monkey module patch. And for C++ users there's an updated header in the 'Code' section on Source Forge (Under the "V1.1" folder). QuickSock should now have no problems running on all of Monkey's C++ desktop targets (Excluding Windows 8 / Window Phone 8).

Duke87(Posted 2013) [#4]
Nice Work really!
I was looking like a week for the Right Networking Module, and here it is :D.
My Problem: I don't understand "native-C++" so i just only could work with your Example and it was really hard to figure out, how to use it for my own project. But in the End, i made a little "Server-App" using Chellenger GUI.
It's the first time i coded with networking stuff, and it worked within the first 5 tries, so i guess ur module is easy enough for newbies to understand if you have time to read your example.

Is it possible to use another network module for Android for example so i can connect a Linux/Win8 Server with Android Smartphones?
Or maybe HTML. (Sorry if the question is stupid, I'm really new to this)

My Aim is to setup a Server at home running on Windows/Linux (GLFW) with your networking module and connect it with a Client_Chat-Software running on HTML5/Android ...

Here is my little Server-App. It works fine with your example.
I've tested it with your example on the Same PC and even on the Laptop connected via WiFi over a Router.
If i'll have time Ill write the Client Program as well

AUTHOR: Duke87 aka Stephan Duckerschein
Date: 7/9/2013

Costum Modules:
- quicksock
Info: QuickSock wrapper V1.1.2(R) STABLE - By: Anthony Diamond (Sonickidnextgen)
Download @ http://sourceforge.net/projects/quicksock/files/?
(downloaded 07.07.2013)

- challengergui (downloaded somewhen in January 2013 ...)
Info: see at http://www.monkeycoder.co.nz/Community/posts.php?topic=2767 - BY: 297Chrisc
Download @ http://www.challenger-arts.com/
Well, As I See, challengerGui is outdated, now its MyGUI.
I'm still using challengerGui as I'm into it. I'll update these Days to MyGui.
ChallngerGui needs the fantomEnginge

My personal testing Network: Everything works via WiFi

| - - Client 1 (192.0.1.xxx)
| (Laptop using Winows 8)
Server - - - - - Router
(Desktop-PC) |
(Winows 7) | - - Client 2 (192.0.1.yyy)
(Laptop using Win 7)

- "DoubleMessage-Problem": if Client1 sends ("Hi") he will receive his own massage back from the Server
- Client_Log: I want to integrate a Window where u can see, who is connected with the Server, and on what status he is.


' Imports:

' Official imports:
Import brl
Import os
Import mojo

' Custom imports:
Import quicksock
Import challengergui

' Preprocessor related:
#GLFW_USE_MINGW = True 'if false => I get a Compile Error (I am too lazy for setting up correctly as MinGW works)


' ### GUI ELEMENTS ###
Global MainWindow:CHGUI 'MainWindow in which the whole Server Stuff will be Rendered and updated
Global Tab_Options:CHGUI 'Options_Tab << Will be integrated later
Global Tab_Server:CHGUI 'Server_Tab (showing the Chat_Log, an Input_Textfield and a SendButton)

' Elements for the Server_Tab
Global Server_Btn_Send:CHGUI '
Global Server_TextBox_Log:CHGUI 'TextBox indem die Chatnachrichten angezeigt werden
Global Server_Inputfield_Message:CHGUI 'Inputfeld zum eingeben neuer NAchrichten

Well, i guess in future The ChatServer won't need a Send button and Inputfield.
The future task for the Server will be just to log the Chat's between the Clients.

Function Main:Int()
New FunChat_Server
Return 1
End Function

' ### Application Class ###
Class FunChat_Server Extends App

' ### Datatype Stuff ###
' Globals/Constants:

' Networking related: (just took the Sonickidnextgen specs, because it worked perfectly by the first time --- never Change a winning Team :D)
Const UPDATE_RATE:Int = 30
Const HOST_PORT:Int = 27015
Const CLIENT_PORT:Int = 38016

' Fields:
Field S:QSocket 'Object of QSocket
Field ConnectionIP:String, LastConnectionIP:String 'IP Stuff
Field Connected:Bool
Field isServer:Bool '= True 'as this is the Server, it should be always True :D
Field ModePicked:Bool 'Not realy sure wether this is necessary for my Project
Field ModeString:String, LastModeString:String
Field ConsoleInput:String, LastConsoleInput:String, Messaging:Bool
Field Nickname:String = "SERVER" 'Nickname should always be SERVER

' ### METHOD Stuff ###

' Mojo methods:
Method OnCreate:Int()
'Will be called at the Start of the Application

'Initing Socket

If (QSocket.SocketsInitialized = False) Then
Error("Sockets failed to initialize.")

'Define Socket Object
S = New QSocket

' ### Creating the visualstyle of the GUI ###
'Main Window
MainWindow = CreateWindow(0,0,DeviceWidth(),DeviceHeight(),"Fun Chat 1 ",0,0,0,0)

Tab_Server = CreateTab("Server",MainWindow)
Tab_Options = CreateTab("Options",MainWindow)

'Chatlog Stuff
Server_TextBox_Log = CreateListbox(10,60,700,500,Tab_Server)
Server_Inputfield_Message = CreateTextfield(10,580,650,25,"",Tab_Server)
Server_Btn_Send = CreateButton(670,580,50,20,"Send",Tab_Server)


Return 1
End Method

Method OnUpdate:Int()

'Updateing the Chellenger GUI (ButtonClicks, Mouseovers etc.)

' Check for termination:
If (KeyHit(KEY_ESCAPE) Or KeyHit(KEY_CLOSE)) Then OnEnd(); Return 1

' Networking related:
If (Connected) Then
' Update the socket:
If (S <> Null) Then S.Update()

'Start up Hosting the Server
If (Connected = False) Then ' Server

'As far as i could figure out, this is the "If there's a Message-Routine" :D
If (S <> Null And Connected = True) Then
If (S.MsgAvail()) Then

Local MSGIN:String = S.ReadLine() 'Store the incoming Message to MSGIN

CreateListboxItem(MSGIN,Server_TextBox_Log) 'Create a new ChatLog-Item with this Message

'return the Message from Client to all Clients
'Problem: The Client who has sent this, gets this message back at the moment. will concentrate on this Later
If (S.IsServer) Then


'Checking if the "Send-Button" is beeing Clicked
If Server_Btn_Send.Clicked Then
Local iText:String = Server_Inputfield_Message.Text 'Get the String of the Input_Textfield
Local Sender:String = "SERVER"

S.WriteLine(Sender +": "+ iText) 'Write the text to the Socket-Stream

S.BroadcastMsg(CLIENT_PORT) 'Send the Stream to the Clients
CreateListboxItem("Out: " + iText ,Server_TextBox_Log) 'Write the outgoing Message to the Server_Log as well
End If


Return 1
End Method

Method OnRender:Int()

'Rendering the Challenger GUI Stuff

Return 1
End Method

'If the App will be terminated
Method OnEnd:Int()
If (Connected = True And S <> Null) Then
Select S.IsServer
Case True
S.WriteLine("SERVER NOTICE: The server has shutdown.")
If (Nickname <> "") Then
S.WriteLine("CLIENT NOTICE: " + Nickname + " has left the chatroom.")
End Select

If (S <> Null) Then S.Close()


Return 0
End Method

Method StartupServer:Bool()
Return StartupHost()
End Method

Method StartupHost:Bool()
If (Connected = False) Then
Connected = S.Host(HOST_PORT)
Return Connected

Return False
End Method

End Class

Keep on! And very much thank for your OpenSource Module
Sorry for bad english.

Why0Why(Posted 2013) [#5]
A lot of folks here usually use something else for the server side. Blitzmax is one. I also would recommend MS products. You can get the express versions for free. It is fairly easy to knock up a nice server in vb.net or C#.

Soap(Posted 2013) [#6]
Erlang is a really good choice for servers—especially anything related to chat. http://veldstra.org/whyerlang/

Many modern techs which have high fault tolerance and concurrency built in are also good choices. I would stay far away from anything which doesn't have those two things as part of their foundation.

marksibly(Posted 2013) [#7]
Just curious why you guys aren't using brl.socket?

ImmutableOctet(SKNG)(Posted 2013) [#8]

Mark Sibly: Just curious why you guys aren't using brl.socket?

QuickSock was initially released before you added socket functionality, thus the reason for the Monkey wrapper. I use it today because my code was already written with it, and I like to have complete control. And, it's available to any C++ developer, so you'll get the same experience with C++ (With or without Monkey). I also made it a bit more streamlined than BRL.Socket. It's also 100% open source, and C++ developers can improve Monkey developers' experiences.

The real question is "Why should we use BRL.Socket?". Sure, if this wasn't my library, and I was just starting to write UDP socket code, I would go with BRL.Socket, but I don't see anything wrong with using a 3rd party library/module. People used 3rd party modules/libraries all the time with BlitzMax and BlitzBasic.

I'm currently working on a reliable (UDP based) high-level networking module, and it relies on QuickSock and ANet. However, if there's enough interest in it, I may add support for BRL.Socket.

Perhaps the biggest downside with using QuickSock is the fact that it's an unofficial project, but since this is my own project, and I rely on it heavily, I'll make sure to keep it stable.

That being said, I forgot to add a 'Free' command in the latest public build, so there's probably a bit of a memory leak going on (Nothing major though). This is fixed in the version I'm working on, but I'll need to finish IPV6 support to release this (Not sure if I can get IPV6 working with Monkey or not). This version also supports Visual Studio 2010/2012 with the XP toolset without having to use Monkey. VS2012 users using the XP platform toolset will have to enable QSOCK_WINDOWS_LEGACY (Define it and set it to 1).

At the end of the day, I did this because there weren't options for UDP in Monkey; that was one of the main reasons I made the leap into programming with C and C++.

I'll probably make QuickSock into a wrapper for BRL.Socket at some point, and just keep it as a C++ library.

Sub_Zero(Posted 2013) [#9]
I'm currently working on a reliable (UDP based) high-level networking module, and it relies on QuickSock and ANet. However, if there's enough interest in it, I may add support for BRL.Socket.

I'm happy to see that ANet could be to any use of anything ;)

Rushino(Posted 2013) [#10]
There is also WebSockets... don't underestimate websockets!

ImmutableOctet(SKNG)(Posted 2013) [#11]

Rushino: There is also WebSockets... don't underestimate websockets!

Well, WebSockets would be great if there was support for UDP. I have heard of things like WebRTC though, and that could possibly work. I'm kind of reluctant to use TCP because of my bad experiences with it. Plus, part of the charm of my new networking module is the fact that it's reasonably fast and optionally reliable. I may look into BRL.Socket and sockets with Flash though.

For those who are wondering, here's a rundown of most of the features so far:
* Support for both GLFW, and Android. (Like I said before, I may support BRL.Socket if there's enough interest)
* Basic encryption (Currently only RC4, but it's pretty modular)
* Automated connection pinging and disconnection handling. (If it wasn't obvious already, this is for servers)
* Faked peer-to-peer messaging. (Clients can send messages to each other manually, or through a reply)
* Optional reliable messaging.
* Internal and external packets. (Used for basic things like pinging, and initializing; nothing useful to the average user)
* A somewhat interesting "virtual address" system (Mainly for clients).
* The possibility to write packets yourself (As long as you conform to my basic internal header standards)
* Basic messaging security. (You have to identify as a client to work with the server. All packets from unidentified sources are considered join requests.)
* Optional encrypted password identification.
* Both integer and string IP support for most features. (Converts to strings anyway)

marksibly(Posted 2013) [#12]
> The real question is "Why should we use BRL.Socket?"

I was really just curious if BRL.Socket was 'missing' anything.

But the major 'plus' to using BRL.Socket is that it works on android, ios, win8 too...

ImmutableOctet(SKNG)(Posted 2013) [#13]
Wait, it works on iOS? I had no idea it supported it, now I'll definitely look into adding it to my module. I'll probably just add an option to rely on BRL.Socket for Android and GLFW. I was thinking of programming iOS support myself, but if BRL.Socket supports it, I don't really need to.

EDIT: Looking over some of the commands, it seems you're using BRL.DataBuffer, I'm already using it, so this should be easy enough.