public void Start() { IsStart = true; reTryCount = 0; ReceiveStage = XmodemReceiveStage.WaitForFirstPacket; SendStage = XmodemSendStage.WaitReceiveRequest; msgQueue.Clear(); TransThread = new Thread(new ThreadStart(TransThreadHandler)); TransThread.IsBackground = true; TransThread.Name = "XmodemTransThread"; TransThread.Start(); if (xmodemInfo.TransMode == TransmitMode.Receive) { if (StartReceive != null) { StartReceive(xmodemInfo, null); } } }
void ReceiveHandler() { if (ReceiveStage == XmodemReceiveStage.WaitForFirstPacket) { if (reTryCount % 2 == 0) { xmodemInfo.CheckMode = XModemCheckMode.CheckSum; SendKEYC(); } else { xmodemInfo.CheckMode = XModemCheckMode.CRC16; SendNAK(); } } XmodemMessage msg = null; lock (msgQueue) { if (msgQueue.Count > 0) { msg = msgQueue.Dequeue(); } } if (msg != null) { reTryCount = 0; switch (msg.MessageType) { case XmodemMessageType.PACKET: ReceiveStage = XmodemReceiveStage.PacketReceiving; SendACK(); if (ReceivedPacket != null) { PacketEventArgs e = msg.Value as PacketEventArgs; ReceivedPacket(xmodemInfo, new PacketEventArgs(e.PacketNo, e.Packet)); } // 通知发下一包 if (SendNextPacket != null) { SendNextPacket(xmodemInfo, null); } break; case XmodemMessageType.PACKET_ERROR: SendNAK(); // 通知重发 if (ReSendPacket != null) { ReSendPacket(xmodemInfo, null); } break; case XmodemMessageType.EOT: SendACK(); // 通知完成 if (EndOfTransmit != null) { EndOfTransmit(xmodemInfo, null); } break; case XmodemMessageType.CAN: SendACK(); // 通知中止 if (AbortTransmit != null) { AbortTransmit(xmodemInfo, null); } break; default: break; } } else { if (waitReceiveEvent.WaitOne(3000)) { waitReceiveEvent.Reset(); } else { reTryCount++; if (reTryCount > RetryMax) { IsStart = false; //通知接收超时 if (TransmitTimeOut != null) { TransmitTimeOut(xmodemInfo, null); } } } } }