MNet - a simple networking module

Monkey Forums/User Modules/MNet - a simple networking module

Xaron(Posted 2011) [#1]
Hi all,

I've started a small networking lib called MNet (Monkey Net):

At the moment it supports only HTTP GET requests on Android so almost nothing but this will change over time.

First I'd like to get this http stuff running on all platforms...

slenkar(Posted 2011) [#2]
You could include indiepaths code, that does http requests on flash and html5

Xaron(Posted 2011) [#3]
I'd do but the download link is dead.

Xaron(Posted 2011) [#4]
I just added HTML5 as a target.

At the moment I use blocking (synchronous) calls only. This will change, especially as XMLHttpRequest in HTML5 doesn't seem to support timeouts...

Loofadawg(Posted 2011) [#5]
Trying your example but the I am getting an error during the Android's compile process:


Any ideas?

The HTML5 compiles without a hitch, but when I execute it the output is "result: undefined"
I don't believe that is the intended result.

Xaron(Posted 2011) [#6]
Holy cow, now that was stupid. Had an old file for checkin. Will be fixed in a few minutes - at least for Android.

Regarding HTML5: Yeah, I just noticed this as well. Strange enough it works sometimes then not... Will check that, thanks!

Ok, XMLHttpRequest() seem to work perfectly with IE9, but not with Firefox 4.x...

Xaron(Posted 2011) [#7]
Ok, please download it again. Android should work now.

Loofadawg(Posted 2011) [#8]
Yeah, I am using Firefox. Will try with IE.

So here we go, cross your fingers & toes:

building for Android...
running App...


It Works !!

<!doctype html><html><head><meta http-equiv="X-UA-Compatible" content="IE=9"><meta http-equiv="content-type" content="text/html; charset=UTF-8"><title>Google</title><script>{ ...yada..yada.yada

And just to verify, Firefox buggers out and with Explorer everything is

Xaron(Posted 2011) [#9]
Wohoo! Well this HTML5 XMLHttpRequest is still very young. There might be better ways to do that. What really bothers me is that IE9 seems to be the only one being able to do it. Neither Firefox 4 nor Google Chrome seem to work with that yet...

Anyway, will see that I add this for iPhone and GLFW next...

Qcat(Posted 2011) [#10]
Looks an interesting project! I have been trying to figure out how to add online high scores to my game so this is just what I have been looking for.

Xaron(Posted 2011) [#11]
I just added the iOS target. :)

Could only test with the simulator so it would be nice if someone could try this on a real device please?

Neuro(Posted 2011) [#12]
Does anyone have any example code on how to actually get this code work with an online score system?

slenkar(Posted 2011) [#13]
you have to write php scripts to put the scores into the database of your website (i recommend haxe to write php scripts).

So you go into the control panel of your website, create database, write the php scripts to accept numbers from a httprequest and insert them into the database, then you write the httprequest from monkey and it should work.

Xaron(Posted 2011) [#14]
I will post some examples when I find some time.

Xaron(Posted 2011) [#15]
Right will post an example tonight, have the code ready.

Xaron(Posted 2011) [#16]
And here is the online highscore list example:

FlameDuck(Posted 2011) [#17]
<blockquote>Ok, XMLHttpRequest() seem to work perfectly with IE9, but not with Firefox 4.x...</blockquote>Also note that for non-ASCII characters many browsers expect the result to be in utf-8 (regardless of http headers or document declaration).

c.k.(Posted 2011) [#18]
Does mnet not work with chrome right now? I'm trying the sample and it's returning "Undefined" for ""

c.k.(Posted 2011) [#19]
Something's wrong with this board's time tracking. I did not post the previous message 40 minutes ago!!! (which is what it's telling me right now).


Samah(Posted 2011) [#20]
Something's wrong with this board's time tracking. I did not post the previous message 40 minutes ago!!! (which is what it's telling me right now).


Every month at the start of the month, all the post times go whack. You'll get used to it. ;)

c.k.(Posted 2011) [#21]

mnet doesn't seem to work in Chrome. Is that right?

I'm trying the sample and it's returning "Undefined" for ""

Goodlookinguy(Posted 2011) [#22]
Google Chrome seems to have some issues with sending requests outside the domain of the website it's in. It might be a built in security feature to prevent an XSS attack. Requests from the website it's in work just fine. So if you want cross-domain requests, you'll need to do it from the server side in the php script.

Also, since I haven't seen MNet updated with a POST request for HTML5. I added it myself. If you want it, you can add this.



pinete(Posted 2011) [#23]
Thanks Goodlookinguy! appreciated ;)

Volker(Posted 2011) [#24]
Trying here to get the httpget example running
on a Motorola Milestone Android.
It crashes on the line:
'result = mnet.HttpGet( "", 3000 )'

Any ideas?

Xaron(Posted 2011) [#25]
Have you set the permissions in the xml template to give the app internet access?

Volker(Posted 2011) [#26]
No. Thanks :-)

Cheese(Posted 2011) [#27]
Hey, I've been watching this on Google Code for a while and I was wondering if you had any perceivable plans in mind to implement TCP/UDP based connections? (For at least GLFW or XNA to start)

I mainly ask this because I'm no expert with networking by the use of HTTP requests. (Anything beyond using this for leader-boards just isn't within my knowledge base)

I'd like to somehow implement communication with a server built in monkey for a specific target in mind.
The reason for the server being programmed in monkey is so it could share many of the same elements of the game, effectively emulating the gameplay to make the implementation of latency correction and anti-cheating measures easy and precise.

As for the more exotic platforms: I believe most massively multiplayer flash games communicate with an XML socket server to operate, and many HTML5 applications communicate with an XMPP server to achieve better results than from simply communicating with a typical web server.

Kind regards,
- Brandon.

Xaron(Posted 2011) [#28]
I have plans to do this, yes. Will take some time as I have other things to do. ;) Any help is appreciated!

pinete(Posted 2011) [#29]
This seems an amazing functionality from my honest opinion, as right now communication with web is a great lack of monkey, and just having a look around, a bunch of games nowadays needs these kind of features.
Unfortunately my knowledge is not as deep as I would like, be sure I would help you if I could.
By the way, you've my moral support in any case, I know is not much but be sure I will be a happy user of whatever the improvements you make on mnet.

Xaron(Posted 2011) [#30]
Thanks! :)

pinete(Posted 2011) [#31]
Hi Xaron,
any update of Mnet to make us happy?? ;)

Fred(Posted 2011) [#32]
Thank you Xaron ! My online highscores and registration system work perfectely with Chrome (based on your example).

Any plan to make it for glfw target ? (or anyone else ?)

Xaron(Posted 2011) [#33]
Yep yep, this will still take some time as I have other stuff to do, but yes, my plans are to make it available for all targets and even real communication stuff (sockets).

Xaron(Posted 2011) [#34]
Alright, I've started to work to integrate real sockets. Will take some time but this will be useful to have some real TCP (and UDP) communication protocol.

Cheese(Posted 2011) [#35]
That sounds great, Xaron; can't wait to test it out!

Neuro(Posted 2012) [#36]
Odd...I just ran the example and got results undefined. Did something change?

Michael(Posted 2012) [#37]
I had this problem for a while with mnet, moofoo & other until I realised the following: you have to ensure the called script is on the same server as the Monkey program that's calling it. It's a security issue (denying cross-site access). Try uploading the Monkey script & your PHP (or similar) to your server & try it.

Neuro(Posted 2012) [#38]
I just uploaded it, still getting the Undefined :

Michael(Posted 2012) [#39]
I can't remember whether I overcame this or not using mnet - I'm using moofoo these days, and it works in the way I mentioned. I guess I must have hence the reason I'm using moofoo instead.

Aman(Posted 2012) [#40]
What's moofoo?

Michael(Posted 2012) [#41]
Just do a search here for it & you'll find the links to it. It's another network lib you can use.

Xaron(Posted 2012) [#42]
I never got HTML5 to work with Networking beside with IE9. Don't know what's wrong there. I still research the socket stuff for now. :)

Xaron(Posted 2012) [#43]
Good news!

I'm near to finish the Pubnub integration for Android (iOS and probably WP7 will follow)! HTML5 and Flash is already done by Skn3, thank you for that and thanks for pointing me to Pubnub!

Using Pubnub almost everything will be possible including real time games with peer to peer, client/server, whatever you can imagine. :)

More to come!

Cheers - Martin

slenkar(Posted 2012) [#44]
potentially you could send the players each others IP address using PubNub and then just send socket messages

Skn3(Posted 2012) [#45]
Oh just to avoid any headaches in the future, the flash pubnub module that is available officially on their website didn't include the channel history protocol so if you try updating the lib at some point make sure to copy the code modificationss over.

I reckon it could be quite a stright forward little project to write a pubnub server emulator (eg to intercept remote pubnub calls) in nodejs or even blitzmax. I did start pondering making one before I slapped myself into sense and got on with paid work.. haha!

Xaron(Posted 2012) [#46]
Thanks Skn3.

I've successfully integrated Android and will update Mnet soon.

Skn3(Posted 2012) [#47]
brilliant, any plans for ios :) ?

Xaron(Posted 2012) [#48]
Sure, iOS will be next followed by WP7. :)

Xaron(Posted 2012) [#49]
Ok, a new version is out!

I've added Pubnub to Android and HTML5 which works together hand in hand. A very basic and simple example is attached as well!

Please note that you can only use one channel at the moment but you can switch between several channels by subscribing to a new one (That's due to the blocking nature of Subscribe for Android).

Thanks Skn3 again for pointing me on this and providing me with the HTML5 version! I hope you don't mind that I use your keys in the examples?

Skn3(Posted 2012) [#50]
Hey Xaron,

good work! I have no experience with the android side of things, but surprised that the subscribe is blocking! Could they be placed in threads and managed by the glue?

I don't mind if you are using my keys, but it might be better to create some ones specific to mnet for going forward with the module :)

Xaron(Posted 2012) [#51]
Ok, I'll create my own set of keys. :)

Yes, Subscribe is blocking for Java and I already placed it into its own thread so the call from Monkey is non-blocking of course.

Sure it will be possible to have several channels open at the same time but I haven't implemented that yet but will do that later.

edit: Ok, I've replaced your keys!

Xaron(Posted 2012) [#52]
...adding sockets (TCP) for GLFW (Windows only) and Android right now, followed by iOS. Shouldn't take too long.

Skn3(Posted 2012) [#53]
Your a machine! :D keep it up!

Xaron(Posted 2012) [#54]
LOL, I know. Ask my wife. ;)

GLFW sockets are working now (both TCP server and client). :) Now to Android.

Tibit(Posted 2012) [#55]
That is solid Xaron, you rule :)

I attempted to make a GIT clone of the Google Code Repository, to see if I could help adding and improving, but I get an error the repository does not exist.

I'm new to GIT so maybe I'm doing something wrong. I clicked the "Source" Tab in GoogleCode and then pasted that Git url into the Clone Adress in my client.

Skn3(Posted 2012) [#56]
LOL, I know. Ask my wife. ;)

Haha filth!

Tibit(Posted 2012) [#57]
In Reply to Myself Above. I was using GIT, but the repository was using HG. Conclusion: They are not the same. Problem Solved.

Xaron(Posted 2012) [#58]
Hehe, yes. I like HG more than GIT even though both are quite good.

Xaron(Posted 2012) [#59]
Ok guys, I just uploaded the sockets part for GLFW including an example. At the moment TCP sockets only work for GLFW, I'll do the Android part next.

I've added a very simple example. So be sure to first create the server by setting the following line in the sockets.monkey example:

Global isServer:Bool = True

Run that piece then compile another sockets.monkey as client (isServer = False). Run as many clients as you want.

In the example you can simply enter a text both on server and client.

Please let me know if there are any bugs (I'm sure there are. ;) )

Xaron(Posted 2012) [#60]
Alright, Android client sockets are almost working now.

I think I will leave it to the client component for Android as server sockets doesn't seem to make sense for me for Android, or what do you think?

For now I thought about having a stdcpp or GLFW server running where all mobile devices can connect to.

MikeHart(Posted 2012) [#61]
Add server sockets for Android too. Think about peer to peer game play. One hosts and the other joins.

Tibit(Posted 2012) [#62]
Xaron would it make sense if one wants to host a game over the local WiFi net with friends nearby in addition to using bluethooth?

Client sockets should be priority anyhow :)

Xaron(Posted 2012) [#63]
Yes, Bluetooth is planned too! So many things... :)

MikeHart(Posted 2012) [#64]
While bluetooth is cool, i still have to see a device, where it doesn't suck the battery badly.

wmaass(Posted 2012) [#65]

I'm having an issue compiling for iOS - getting some errors "Mnet is not polymorphic". I am just trying to use the HTTP stuff. Advice?

Tibit(Posted 2012) [#66]
Is there even an iOS port yet?

wmaass(Posted 2012) [#67]
Since 1.03 I think. Xaron notes in a post above that he hasn't tried it on a device yet though. I should clarify that Monkey compiles fine but XCode produces the not polymorphic error.

Xaron(Posted 2012) [#68]
Ah right. Sorry for that. Must had happened during my refactoring. Will fix that.

I plan to add Pubnub iOS as well.

wmaass(Posted 2012) [#69]
Cool, thanks Xaron. Pubnub looks interesting.

Xaron(Posted 2012) [#70]
Yep, Pubnub is awesome. They cover a lot of problems you usually have with networking. Should be ok for "normal" usage like for turn based games. For action games it might become a bit pricey though...

Xaron(Posted 2012) [#71]
Things slow down a bit at the moment as my son got a brother. :)

wmaass(Posted 2012) [#72]

Richard Betson(Posted 2012) [#73]

All good stuff here:D

Xaron(Posted 2012) [#74]
Thanks guys. :)

Lugato(Posted 2012) [#75]
Hi Xaron,

can you give me a help ?

I'm trying to add pubnub in my app using your module, when I run your example program, all things working nice, but when I try put the code in my app I'm give this error:

Monkey runtime error: ReferenceError: Can't find variable: PUBNUB

you have a idea of what I'm made wrong ?


Rus(Posted 2012) [#76]
Hi Xaron! Great work on mnet. It works like a charm on HTML5. Unfortunately I'm running into a bug with android. These are the details:
- I'm using mnet-v1.2.0.
- I've done a debug build of the pubnub example.
- I click on Subscribe to channel 1.
- Then I click on Subscribe to channel 2.

This produces a Monkey runtime error: Unknown runtime error.
It points at pubnub.monkey line 80, which reads:

[monkeycode]pn.Subscribe( CHANNEL_2 )[/monkeycode]
Not being a java programmer myself, I don't really understand what's happening. Any help would be much appreciated!

Xaron(Posted 2012) [#77]
@Rus: I'll check this!

@Lugato: Have you tried HTML5?

Lugato(Posted 2012) [#78]

I´m using html to test the app, the error occour if I try run the projetct in the monkey IDE. If you need I can send to you the code ..


Rus(Posted 2012) [#79]
Thanks Xaron! Would be great to get pubnub working smoothly for my app. Cheers!

dirkk(Posted 2012) [#80]
To get the httpget to work on Android, do not forget to set the permission for the app to use the internets:

a) After your first compile, in your build folder you should see a templates folder, alter the AndroidManifest.xml file in there.
(thx therevills )

b) Add these lines:
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

(thx therevills again )

Skn3(Posted 2012) [#81]
How goes the socket aspects of mnet? Btw congratulations on your new son!

Neuro(Posted 2012) [#82]
Can anyone get Mnet to work on platforms like GLFW? Or is this not supported yet?

Skn3(Posted 2012) [#83]
I think it already has sockets and pubnub on glfw.

FelipeA(Posted 2012) [#84]
I get an error on the glfw socket demo.
I hope the socket support extends to the other targets, it would be awesome!

Xaron(Posted 2012) [#85]
It will! Takes some time though. I will add Pubnub for iOS and WP7 first.

c.k.(Posted 2012) [#86]
I'm trying to use mnet on android, and it's returning a Null object when I use the following code:


Method GetGameID:Int(gname:String)
Local gid:Int = -1
Local resultString:String
Local mess:String = scoreURL+"?action=GETGAMEID&gameName="+gname
resultString = ht.Get( mess ) ' <-- here's the problem
If resultString.Length() > 0 Then
Local rt$[] = resultString.Split(";")
If Int(rt[0]) > -1 Then
gid = Int(rt[1])
Return gid

Apparently, Get() is returning a Null object (for whatever reason). The Java source for Get() looks like this:

public String Get( String url, int timeoutConnection, int timeoutSocket )
    HttpURLConnection con = null;
    InputStream is = null;
      URL connectToURL = new URL( url );
      con = ( HttpURLConnection )connectToURL.openConnection();
      con.setReadTimeout( timeoutSocket );
      con.setConnectTimeout( timeoutConnection );
      con.setRequestMethod( "GET" );
      con.setDoInput( true );
      // Start the query
      is = con.getInputStream();
    catch( IOException e )
      _result = "ERR_HttpGet " + e.getMessage();
    return convertStreamToString( is );

Do I change my monkey code so it handles the Null object being returned (and how?), or do I modify the Java source so it returns an empty string if an error occurs (and how)?

Thanks! :-)

tOmzone(Posted 2012) [#87]
Did anybody get the socket example running yet? As already mentioned there are some methods missing or named incorrectly. Even after renaming "ReceiveFromClient()" to "Receive()" (this method does exist) it does not work.

I tried for several hours now and cant establish a simple connection between server and client.

Xaron(Posted 2012) [#88]
You mean that GLFW sockets example? That should work.

tOmzone(Posted 2012) [#89]
Ahh, problem solved, it was my bad!

I tried to receive messages by using Receive() even if no client was connected to the server. I thought it would just return an empty string then but the server refused incoming connections then.

c.k.(Posted 2012) [#90]
Show me some love? :-)

tOmzone(Posted 2012) [#91]
I dont get it...
Client can now connect to the server but when it sends a message to server the server closes the connection to the client.
(GetNumberOfClients() returns 0 after receiving a message)

Dan(Posted 2012) [#92]
I keep getting the polymorphic error in IOS. Is there a certain version that does not get that error? Is there a certain version of IOS xcode I need to be using?

tOmzone(Posted 2012) [#93]
Hi Xaron,

could you please try this example and tell me what i'm doing wrong here?
Its just a simple server and client and the client shall send a message if space is being pressed.

Import mnet
Import mojo

Function Main()
	New Program

Class Program extends App

	Field server:Socket
	Field messages:List<String> = new List<String>()
	Method OnCreate()
		server = New Socket()
	Method OnUpdate()
		Local m:String = server.Receive()
		if m <> "" Then messages.AddLast(m)
		if KeyDown(KEY_ESCAPE)
	Method OnRender()
		SetColor(255, 255, 255)
		DrawText("server", 10, 10)
		DrawText("clients: " + server.GetNumberOfClients(), 10, 30)
		DrawText("client: " + server.GetLastClient(), 10, 45)
		Local y = 65
		DrawText("Messages:", 10, y)
		For Local m:String = eachin messages
			y += 20
			DrawText(">" + m + "<", 10, y)


Import mojo
Import mnet

Function Main()
	New Program

Class Program extends App

	Field connection:Socket
	Method OnCreate()
		connection = New Socket()
		connection.ConnectToServer("localhost", 644)
	Method OnUpdate()
		if KeyHit(KEY_SPACE)
		if KeyDown(KEY_ESCAPE)
	Method OnRender()
		SetColor(255, 255, 255)
		DrawText("client", 10, 10)


When space is pressed on clientside, the server loses the connection to client! Could you please have a look at that? Thank you

Sub_Zero(Posted 2012) [#94]
Is socket implemented for android?

Xaron(Posted 2012) [#95]
Sockets for Android and iOS are on my list, at least the client side for now. GLFW sockets are done. I already have the Android sockets running but it's still buggy, so sit tight! ;)

@tOmzone: Sorry for the late answer will look into this.

@Dan: Oops, looks broken. Will fix that.

Unfortunately I'm a bit limited with my time at the moment due to my litte son. ;) But over the time it will become a powerful (and of course free) lib!

Dan(Posted 2012) [#96]
Can't wait! Thanks Xaron!

Skn3(Posted 2012) [#97]
keep up the good work when your good and ready!

Rushino(Posted 2012) [#98]
Is this still under developement ? I tried your module but it actually crash on the method ReceiveFromClient() from the socket file.

Xaron(Posted 2012) [#99]
Does it? Damnit. Well I think I make a huge rewrite of all this stuff. Monkey can do TCP stuff out of the box now so I think I'll concentrate more on stuff like Bluetooth.

Midimaster(Posted 2012) [#100]
I'm doing a lot of experiment now with Mnet on Android and Html5. Everything is working fine, but if the connection fails during a game it is difficult to handle this, because MNET return a "undefined" String.

Every attempt to handle this in monkey ends in a crash.

It is not possible to test...

[monkeycode]Result$=Http.Get( Adress, 3000 )
If Result=NULL[/monkeycode]

[monkeycode]Result$=Http.Get( Adress, 3000 )
If Result[/monkeycode]

[monkeycode]Result$=Http.Get( Adress, 3000 )
If Result[..3]="abc" ' to dected it was ok...[/monkeycode]

but this works:
[monkeycode]Result$=Http.Get( Adress, 3000 )
Print Result[/monkeycode]
you will see the word "undefined" in the Console

I would like to know how to handle "undefined" strings. Why is there no test against "undefined", but the console knows this state?

As a workaround I had to change some code in the JAVA and JS native code:
  public String convertStreamToString( InputStream is )
// this line is new, java seems to handle undefined as NULL:
	if (is == null) return "ERROR no Connection";

    StringBuilder sb = new StringBuilder();
      BufferedReader reader = new BufferedReader( new InputStreamReader( is ) );
      String line = null;
      while( ( line = reader.readLine() ) != null )

MNet_Http.prototype.Get = function( url, timeoutConnection, timeoutSocket )
    var client = new XMLHttpRequest(); "GET", url, false );
    client.send( null );
    _httpResponse = client.responseText;
    return _httpResponse;
  catch( e )
// this line is new. Author forgot to return something, when a error occurs:
  	return "ERROR no Connection";

with this you can Check in Monkey
[monkeycode]Result$=Http.Get( Adress, 3000 )
If Result[..3]="ERR" ' to dected it occured an error...[/monkeycode]

MikeHart(Posted 2012) [#101]
MNET could send back an empty string. I am not at my dev system, but i had modified MNET exactly to do this because it was returning undefined strings.

frank(Posted 2013) [#102]
GLFW target: Under xcode 4.2.1 I get these kind of errors:

main.cpp:3642: error: ‘SOCKET’ does not name a type
main.cpp:3644: error: ‘SOCKADDR_IN’ does not name a type

in Stackoverflow they said that these are only defined for Windows?

I don't know enough to fix this; any ideas?

typedef int SOCKET;

works but there are a LOT of others :)

ziggy(Posted 2013) [#103]
Am I the only one that is getting a virus alert whenever I visit this thread?

rIKmAN(Posted 2013) [#104]
No virus alert here, using Chrome and AVG.

frank(Posted 2013) [#105]
No virus!

I decided to sidestep the issue with mnet by using mnet only for html5 target and brl for the rest. Bit messy though :)

OvineByDesign(Posted 2013) [#106]
no virus here - im using ESET too


Rushino(Posted 2013) [#107]

Maybea false positive.

Midimaster(Posted 2013) [#108]
Can somebody please check or confirm, that Mnet is still working on Android 4.0, 4.1, 4.2 devices?

I have massive problems with my app and I guess that MNET causes the problems.

Here is a link to the description of the problem:

*** EDIT ***

It is MNET! The synchron mode of calling http requests is no longer allowed on android 4. The app ends without error message or comment. A possible solution is the async HttpRequest() mode Mark offers since Monkey V69.

Snader(Posted 2013) [#109]
Also getting a Malware detection in Chrome on this page. It's about serving malware.

Xaron(Posted 2013) [#110]
Me too, that's pretty strange. How's that?

Regarding MNet: At the moment I don't work on this as Mark has introduced TCP streaming to Monkey.

Difference(Posted 2013) [#111]
@Moderators: Neuros picture in post #38 is triggering Malware detection in chrome.

can you remove it? ""