public void Send(MessageIn msgIn) { try { if (client != null) { if (!client.IsRunning()) { client.Connect(); client.Start(); } client.Send(msgIn.Build()); if (msgIn.Type != MessageType.Heartbeat) { ServiceManager.Log(JsonConvert.SerializeObject(msgIn)); } } else { ServiceManager.Log("disconnected."); } } catch (Exception ex) { ServiceManager.Error(ex); } }
public bool Connect() { Task.Run(new Action(() => { // 创建一个实例 client = new ConnectClient(this.Config); client.Received += (sender, ByteBuf) => { try { MessageOut msgOut = MessageOut.Parse(ByteBuf); if (msgOut != null) { if (msgOut.Mode != MessageMode.Heartbeat) { ServiceManager.Log(msgOut.ToJson()); } if (msgOut.Mode == MessageMode.Result) { ServiceManager.Resolve <IMessageService>().Completed(msgOut); } else if (msgOut.Mode == MessageMode.Callback) { ServiceManager.Resolve <ICallbackService>().Callback(msgOut); } } } catch (Exception ex) { ServiceManager.Error(ex); } }; lastHeartbeat = DateTime.Now; while (true) { if (client != null) { if (!client.IsRunning()) { client.Connect(); client.Start(); } SendHeartbeat(); } else { break; } System.Threading.Thread.Sleep(10); } })); DateTime start = DateTime.Now; while (client == null || !client.IsRunning()) { if ((DateTime.Now - start).TotalSeconds > 2) { this.Disconnect(); return(false); } System.Threading.Thread.Sleep(10); } return(true); }