static void SendCB(IAsyncResult ar) { try { var ba = _wQueue.Peek(); var sock = ar.AsyncState as Socket; var cnt = sock.EndSend(ar); var str = Encoding.UTF8.GetString(ba.bytes, ba.readIdx, cnt); ba.Move((ushort)cnt); Console.WriteLine($"发送:{str}"); if (ba.Length == 0) { _wQueue.Dequeue(); } ba = _wQueue.Peek(); if (ba != null) { sock.BeginSend(ba.bytes, ba.readIdx, ba.Length, 0, SendCB, sock); } } catch (System.Exception e) { Console.WriteLine(e); } }
public void Send(object msg) { if (_socket == null || !_socket.Connected || _isConnecting || _isCloseing) { return; } var sendBytes = Packer.Encode(msg); _sendQueue.EnqueueFrom(sendBytes); if (_sendQueue.Count == 1) { var node = _sendQueue.Peek(); _socket.BeginSend(node.Bytes, node.ReadIdx, node.Length, 0, SendCallback, _socket); } }
void ProcessBufferedIO(bool force = false) { BufferedIO io; while (WriteQueue.Count > 0) { io = WriteQueue.Peek(); // This means we wanted to wait until all the writes had been flushed // before we attempt to generate the hash of a given piece. if (io.manager == null && io.buffer == null) { io = WriteQueue.Dequeue(); io.tcs.SetResult(true); continue; } if (!force && !WriteLimiter.TryProcess(io.count)) { break; } io = WriteQueue.Dequeue(); try { Interlocked.Add(ref pendingWrites, -io.count); Write(io.manager, io.offset, io.buffer, io.count); io.tcs.SetResult(true); } catch (Exception ex) { io.tcs.SetException(ex); } } while (ReadQueue.Count > 0) { if (!force && !ReadLimiter.TryProcess(ReadQueue.Peek().count)) { break; } io = ReadQueue.Dequeue(); try { Interlocked.Add(ref pendingReads, -io.count); var result = Read(io.manager, io.offset, io.buffer, io.count); io.tcs.SetResult(result); } catch (Exception ex) { io.tcs.SetException(ex); } } }