private void Thread_MonitorStream(LocalBackgroundWorker <object, WorkerResponse> worker) { try { int i; var bytes = new byte[256]; byte[] continueBuffer = new byte[1024 * 1024 * 5]; int bufferIndex = 0; int curPayloadLen = -1; while (true) { while ((i = socket.Receive(bytes)) != 0) { for (var j = 0; j < i; j++) { var b = bytes[j]; continueBuffer[bufferIndex++] = b; if (curPayloadLen == bufferIndex) { var response = WorkerResponse.FromMessage(continueBuffer, bufferIndex); if (response != null) { worker.SendResponse(response); } bufferIndex = 0; curPayloadLen = -1; } else if (bufferIndex == 4) { curPayloadLen = BitConverter.ToInt32(continueBuffer, 0); } } } if (Thread_IsConnected()) { continue; } Thread_Disconnected(worker); break; } } catch (IOException) { Thread_Disconnected(worker); } catch (SocketException) { Thread_Disconnected(worker); } catch (ObjectDisposedException) { Thread_Disconnected(worker); } catch (Exception ex) { Console.WriteLine($"Receive Exception: {ex}"); Thread_Disconnected(worker); } }
public void Start() { socket.ReceiveTimeout = 30000; socket.SendTimeout = 30000; socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 0); awaitMessagesWorker = new LocalBackgroundWorker <object, WorkerResponse>(); awaitMessagesWorker.DoWork += (worker, _) => Thread_MonitorStream(worker); awaitMessagesWorker.ReportResponse += ReceiveResponse; awaitMessagesWorker.Run(); }
private void Thread_Disconnected(LocalBackgroundWorker <object, WorkerResponse> worker) { worker.SendResponse(WorkerResponse.Disconnect()); }