public static void on_message(object ssn) { session s = (session)ssn; long running = s.running; while (running == s.running) { tcp.response rsp = s.tc.recv(); if (rsp == null) { if (!s.tc.isConnected()) { Console.WriteLine("WARN: connection off, on_message will exit."); break; } else { continue; } } lock (s) { tcp.response t = null; if (s.match.TryGetValue(rsp.sn, out t)) { s.match[rsp.sn] = rsp; } else // process the unresolved messages { if (s.handler != null) s.handler.proc(rsp); } } } }
// the message proc public override void proc(tcp.response rsp) { switch (rsp.cmd) { case (short)server.cmd.RSP_QUICKPLAY: // match ok, print the opponent's name { int res = rsp.nextInt(); string opponent = rsp.nextString(); Console.WriteLine("cmd=[{0}], sn=[{1}], result=[{2}], opponent=[{3}]", rsp.cmd, rsp.sn, res, opponent); } break; } }
public result logout(int timeout) { if (!tc.isConnected()) return new result(); tcp.request req = new tcp.request((short)cmd.REQ_LOGOUT); tcp.response rsp = send(req, timeout); if (rsp == null) return new result(); int res = rsp.nextInt(); string msg = rsp.nextString(); Console.WriteLine("cmd=[{0}], sn=[{1}], result=[{2}], errmsg=[{3}]", rsp.cmd, rsp.sn, res, msg); return new result(res==0, msg); }
private tcp.response send(tcp.request req, int timeout /* ms */) { // 1. add to req-rsp match table lock (this) { match.Add(req.sn, null); } // 2. send request if (!req.send(tc)) { lock (this) { match.Remove(req.sn); } return null; } // 3. block wait tcp.response rsp = null; int tick = timeout > 100 ? 100 : timeout; while (tick > 0) { timeout -= tick; Thread.Sleep(tick); tick = timeout > 100 ? 100 : timeout; match.TryGetValue(req.sn, out rsp); if (rsp != null) break; } lock (this) { match.Remove(req.sn); } return rsp; }
public result login(string usr, string passwd, int timeout /* ms */) { if (!tc.isConnected()) { start(); if (!tc.isConnected()) return new result(false, "connection lost"); } tcp.request req = new tcp.request((short)cmd.REQ_LOGIN); req.encode(usr); req.encode(passwd); tcp.response rsp = send(req, timeout); if (rsp == null) { return new result(false, "no response"); } int result = rsp.nextInt(); string errmsg = rsp.nextString(); Console.WriteLine("cmd=[{0}], sn=[{1}], result=[{2}], errmsg=[{3}]", rsp.cmd, rsp.sn, result, errmsg); return new result(result==0, errmsg); }
public abstract void proc(tcp.response rsp);