Skip to content

Instantly share code, notes, and snippets.

@wizzard0
Created September 2, 2012 12:59
Show Gist options
  • Save wizzard0/3598449 to your computer and use it in GitHub Desktop.
Save wizzard0/3598449 to your computer and use it in GitHub Desktop.
microhttp-hx
package crossplatformtest;
import haxe.Log;
import neko.vm.Thread;
/**
* ...
* @author Wizzard
*/
class Main
{
static function main()
{
Log.trace("Server running on port 1234");
/*var x = new Winlog("haXe crossplatform build test");
x.log("Running on "+Sys.systemName());
x.button = "Close";
x.enabled = true;
x.onClick = function() {
Ui.stopLoop();
}*/
socketRunner();
//runThread();
/*
Ui.loop();*/
}
//static function runThread() {
// var t1 = Thread.create(socketRunner);
//}
static function socketRunner() {
var server:SocketServer = new SocketServer();
server.run("0.0.0.0", 1234);
}
}
package crossplatformtest;
/**
* ...
* @author Wizzard
*/
import neko.Lib;
import neko.net.Socket;
import neko.net.ThreadServer;
import haxe.io.Bytes;
import neko.Sys;
typedef Client = {
var id : Int;
var sock : Socket;
}
typedef Message = {
var str : String;
}
class SocketServer extends ThreadServer<Client, Message>
{
// create a Client
override function clientConnected( s : Socket ) : Client
{
var num = Std.random(100);
Lib.println("client " + num + " is " + s.peer());
return { id: num, sock: s };
}
override function clientDisconnected( c : Client )
{
Lib.println("client " + Std.string(c.id) + " disconnected");
}
override function readClientMessage(c:Client, buf:Bytes, pos:Int, len:Int)
{
// find out if there's a full message, and if so, how long it is.
var complete = false;
var cpos = pos;
while (cpos < (pos+len) && !complete)
{
if(cpos>5){
complete = (buf.get(cpos-3) == 13)&&(buf.get(cpos-2) == 10)&&(buf.get(cpos-1) == 13)&&(buf.get(cpos) == 10);
}
cpos++;
}
// no full message
if( !complete ) return null;
// got a full message, return it
var msg:String = buf.readString(pos, cpos-pos);
return {msg: {str: msg}, bytes: cpos-pos};
}
override function clientMessage( c : Client, msg : Message )
{
if (msg.str.indexOf("/quit") > 0) {
Lib.println(c.id + " sent: " + msg.str);
c.sock.write("HTTP/1.1 200 OK\r\nContent-Length: 1\r\nConnection: close\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nQ");
c.sock.close();
Sys.exit(0);
}else {
Lib.println(c.id + " sent: " + msg.str);
c.sock.write("HTTP/1.1 200 OK\r\nContent-Length: 1\r\nConnection: close\r\nContent-Type: text/plain; charset=UTF-8\r\n\r\nA");
c.sock.close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment