View Javadoc

    1   package org.mortbay.cometd.client.ext;
    2
    3   import java.util.Map;
    4
    5   import org.cometd.Client;
    6   import org.cometd.Extension;
    7   import org.cometd.Message;
    8   import org.mortbay.util.ajax.JSON;
    9
    10  public class TimesyncClientExtension implements Extension
    11  {
    12      volatile int _lag;
    13      volatile int _offset;
    14
    15      public Message rcv(Client from, Message message)
    16      {
    17          return message;
    18      }
    19
    20      public Message rcvMeta(Client from, Message message)
    21      {
    22          Map<String,Object> ext=message.getExt(false);
    23          if (ext!=null)
    24          {
    25              Map<String,Object> sync=(Map<String,Object>)ext.get("timesync");
    26              if (sync!=null)
    27              {
    28                  long now = System.currentTimeMillis();
    29
    30
    31                  final long tc=((Number)sync.get("tc")).longValue();
    32                  final long ts=((Number)sync.get("ts")).longValue();
    33                  final int p=((Number)sync.get("p")).intValue();
    34                  // final int a=((Number)sync.get("a")).intValue();
    35
    36                  int l2 = (int) ((now - tc - p) / 2);
    37                  int o2 = (int) (ts-tc-l2);
    38
    39                  _lag=_lag==0?l2:(_lag+l2)/2;
    40                  _offset=_offset==0?o2:(_offset+o2)/2;
    41              }
    42          }
    43
    44          return message;
    45      }
    46
    47      public Message send(Client from, Message message)
    48      {
    49          return message;
    50      }
    51
    52      public Message sendMeta(Client from, Message message)
    53      {
    54          Map<String,Object> ext=message.getExt(true);
    55          long now = System.currentTimeMillis();
    56          JSON.Literal timesync=new JSON.Literal("{\"tc\":"+now+",\"l\":"+_lag+",\"o\":"+_offset+"}");
    57          ext.put("timesync",timesync);
    58          return message;
    59      }
    60
    61      public int getOffset()
    62      {
    63          return _offset;
    64      }
    65
    66      public int getLag()
    67      {
    68          return _lag;
    69      }
    70
    71      public long getServerTime()
    72      {
    73          return System.currentTimeMillis()+_offset;
    74      }
    75
    76  }