Advertisement
PifyZ

Client/Serveur

Jul 31st, 2014
617
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Haxe 1.75 KB | None | 0 0
  1. // Server.hx
  2. package;
  3.  
  4. import neko.Lib;
  5. import sys.net.Socket;
  6. import neko.net.ThreadServer;
  7. import haxe.io.Bytes;
  8.  
  9. typedef Client = {
  10.   var id:Int;
  11. }
  12.  
  13. typedef Message = {
  14.   var str:String;
  15. }
  16.  
  17. class Server extends ThreadServer<Client, Message> {
  18.     // create a Client
  19.     override function clientConnected( s : Socket ) : Client {
  20.         var num = Std.random(100);
  21.  
  22.         Lib.println("client " + num + " is " + s.peer());
  23.  
  24.         return { id: num };
  25.     }
  26.  
  27.     override function clientDisconnected( c : Client ) {
  28.         Lib.println("client " + Std.string(c.id) + " disconnected");
  29.     }
  30.  
  31.     override function readClientMessage(c:Client, buf:Bytes, pos:Int, len:Int) {
  32.         // find out if there's a full message, and if so, how long it is.
  33.         var complete = false;
  34.         var cpos = pos;
  35.  
  36.         while (cpos < (pos+len) && !complete) {
  37.             //check for a period/full stop (i.e.:  "." ) to signify a complete message
  38.             complete = (buf.get(cpos) == 46);
  39.             cpos++;
  40.         }
  41.  
  42.         // no full message
  43.         if (!complete)
  44.             return null;
  45.  
  46.         // got a full message, return it
  47.         var msg:String = buf.getString(pos, cpos-pos);
  48.  
  49.         return {msg: {str: msg}, bytes: cpos-pos};
  50.     }
  51.  
  52.     override function clientMessage( c : Client, msg : Message ) {
  53.         Lib.println(c.id + " sent: " + msg.str);
  54.     }
  55.  
  56.     public static function main() {
  57.         var server = new Server();
  58.         server.run("192.168.0.31", 1234);
  59.     }
  60. }
  61.  
  62. // Client.hx
  63. package;
  64.  
  65. import neko.Lib;
  66. import sys.net.Host;
  67. import sys.net.Socket;
  68.  
  69. class Client {
  70.     public static function main() {
  71.         Lib.println("opening connection");
  72.         var sock = new Socket();
  73.         sock.connect(new Host("192.168.0.31"), 1234);
  74.  
  75.         while (true) {
  76.             var input = Sys.stdin().readLine() + ".";
  77.             sock.write(input);
  78.         }
  79.  
  80.         sock.close();
  81.         Lib.println("client done");
  82.     }
  83. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement