1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069 |
- using System;
- using System.Net;
- using System.Net.Sockets;
- using System.Text;
- using System.Threading;
- namespace NetCoreServer
- {
-
-
-
-
- public class TcpClient : IDisposable
- {
-
-
-
-
-
- public TcpClient(IPAddress address, int port) : this(new IPEndPoint(address, port)) {}
-
-
-
-
-
- public TcpClient(string address, int port) : this(new IPEndPoint(IPAddress.Parse(address), port)) {}
-
-
-
-
- public TcpClient(DnsEndPoint endpoint) : this(endpoint as EndPoint, endpoint.Host, endpoint.Port) {}
-
-
-
-
- public TcpClient(IPEndPoint endpoint) : this(endpoint as EndPoint, endpoint.Address.ToString(), endpoint.Port) {}
-
-
-
-
-
-
- private TcpClient(EndPoint endpoint, string address, int port)
- {
- Id = Guid.NewGuid();
- Address = address;
- Port = port;
- Endpoint = endpoint;
- }
-
-
-
- public Guid Id { get; }
-
-
-
- public string Address { get; }
-
-
-
- public int Port { get; }
-
-
-
- public EndPoint Endpoint { get; private set; }
-
-
-
- public Socket Socket { get; private set; }
-
-
-
- public long BytesPending { get; private set; }
-
-
-
- public long BytesSending { get; private set; }
-
-
-
- public long BytesSent { get; private set; }
-
-
-
- public long BytesReceived { get; private set; }
-
-
-
-
-
-
-
- public bool OptionDualMode { get; set; }
-
-
-
-
-
-
- public bool OptionKeepAlive { get; set; }
-
-
-
-
-
-
- public int OptionTcpKeepAliveTime { get; set; } = -1;
-
-
-
-
-
-
- public int OptionTcpKeepAliveInterval { get; set; } = -1;
-
-
-
-
-
-
- public int OptionTcpKeepAliveRetryCount { get; set; } = -1;
-
-
-
-
-
-
- public bool OptionNoDelay { get; set; }
-
-
-
- public int OptionReceiveBufferLimit { get; set; } = 0;
-
-
-
- public int OptionReceiveBufferSize { get; set; } = 8192;
-
-
-
- public int OptionSendBufferLimit { get; set; } = 0;
-
-
-
- public int OptionSendBufferSize { get; set; } = 8192;
- #region Connect/Disconnect client
- private SocketAsyncEventArgs _connectEventArg;
-
-
-
- public bool IsConnecting { get; private set; }
-
-
-
- public bool IsConnected { get; private set; }
-
-
-
-
-
-
-
- protected virtual Socket CreateSocket()
- {
- return new Socket(Endpoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
- }
-
-
-
-
-
-
-
-
- public virtual bool Connect()
- {
- if (IsConnected || IsConnecting)
- return false;
-
- _receiveBuffer = new Buffer();
- _sendBufferMain = new Buffer();
- _sendBufferFlush = new Buffer();
-
- _connectEventArg = new SocketAsyncEventArgs();
- _connectEventArg.RemoteEndPoint = Endpoint;
- _connectEventArg.Completed += OnAsyncCompleted;
- _receiveEventArg = new SocketAsyncEventArgs();
- _receiveEventArg.Completed += OnAsyncCompleted;
- _sendEventArg = new SocketAsyncEventArgs();
- _sendEventArg.Completed += OnAsyncCompleted;
-
- Socket = CreateSocket();
-
- IsSocketDisposed = false;
-
- if (Socket.AddressFamily == AddressFamily.InterNetworkV6)
- Socket.DualMode = OptionDualMode;
-
- OnConnecting();
- try
- {
-
- Socket.Connect(Endpoint);
- }
- catch (SocketException ex)
- {
-
- SendError(ex.SocketErrorCode);
-
- _connectEventArg.Completed -= OnAsyncCompleted;
- _receiveEventArg.Completed -= OnAsyncCompleted;
- _sendEventArg.Completed -= OnAsyncCompleted;
-
- OnDisconnecting();
-
- Socket.Close();
-
- Socket.Dispose();
-
- _connectEventArg.Dispose();
- _receiveEventArg.Dispose();
- _sendEventArg.Dispose();
-
- OnDisconnected();
- return false;
- }
-
- if (OptionKeepAlive)
- Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
- if (OptionTcpKeepAliveTime >= 0)
- Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, OptionTcpKeepAliveTime);
- if (OptionTcpKeepAliveInterval >= 0)
- Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, OptionTcpKeepAliveInterval);
- if (OptionTcpKeepAliveRetryCount >= 0)
- Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, OptionTcpKeepAliveRetryCount);
-
- if (OptionNoDelay)
- Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
-
- _receiveBuffer.Reserve(OptionReceiveBufferSize);
- _sendBufferMain.Reserve(OptionSendBufferSize);
- _sendBufferFlush.Reserve(OptionSendBufferSize);
-
- BytesPending = 0;
- BytesSending = 0;
- BytesSent = 0;
- BytesReceived = 0;
-
- IsConnected = true;
-
- OnConnected();
-
- if (_sendBufferMain.IsEmpty)
- OnEmpty();
- return true;
- }
-
-
-
-
- public virtual bool Disconnect()
- {
- if (!IsConnected && !IsConnecting)
- return false;
-
- if (IsConnecting)
- Socket.CancelConnectAsync(_connectEventArg);
-
- _connectEventArg.Completed -= OnAsyncCompleted;
- _receiveEventArg.Completed -= OnAsyncCompleted;
- _sendEventArg.Completed -= OnAsyncCompleted;
-
- OnDisconnecting();
- try
- {
- try
- {
-
- Socket.Shutdown(SocketShutdown.Both);
- }
- catch (SocketException) {}
-
- Socket.Close();
-
- Socket.Dispose();
-
- _connectEventArg.Dispose();
- _receiveEventArg.Dispose();
- _sendEventArg.Dispose();
-
- IsSocketDisposed = true;
- }
- catch (ObjectDisposedException) {}
-
- IsConnected = false;
-
- _receiving = false;
- _sending = false;
-
- ClearBuffers();
-
- OnDisconnected();
- return true;
- }
-
-
-
-
- public virtual bool Reconnect()
- {
- if (!Disconnect())
- return false;
- return Connect();
- }
-
-
-
-
- public virtual bool ConnectAsync()
- {
- if (IsConnected || IsConnecting)
- return false;
-
- _receiveBuffer = new Buffer();
- _sendBufferMain = new Buffer();
- _sendBufferFlush = new Buffer();
-
- _connectEventArg = new SocketAsyncEventArgs();
- _connectEventArg.RemoteEndPoint = Endpoint;
- _connectEventArg.Completed += OnAsyncCompleted;
- _receiveEventArg = new SocketAsyncEventArgs();
- _receiveEventArg.Completed += OnAsyncCompleted;
- _sendEventArg = new SocketAsyncEventArgs();
- _sendEventArg.Completed += OnAsyncCompleted;
-
- Socket = CreateSocket();
-
- IsSocketDisposed = false;
-
- if (Socket.AddressFamily == AddressFamily.InterNetworkV6)
- Socket.DualMode = OptionDualMode;
-
- IsConnecting = true;
-
- OnConnecting();
-
- if (!Socket.ConnectAsync(_connectEventArg))
- ProcessConnect(_connectEventArg);
- return true;
- }
-
-
-
-
- public virtual bool DisconnectAsync() => Disconnect();
-
-
-
-
- public virtual bool ReconnectAsync()
- {
- if (!DisconnectAsync())
- return false;
- while (IsConnected)
- Thread.Yield();
- return ConnectAsync();
- }
- #endregion
- #region Send/Receive data
-
- private bool _receiving;
- private Buffer _receiveBuffer;
- private SocketAsyncEventArgs _receiveEventArg;
-
- private readonly object _sendLock = new object();
- private bool _sending;
- private Buffer _sendBufferMain;
- private Buffer _sendBufferFlush;
- private SocketAsyncEventArgs _sendEventArg;
- private long _sendBufferFlushOffset;
-
-
-
-
-
- public virtual long Send(byte[] buffer) => Send(buffer.AsSpan());
-
-
-
-
-
-
-
- public virtual long Send(byte[] buffer, long offset, long size) => Send(buffer.AsSpan((int)offset, (int)size));
-
-
-
-
-
- public virtual long Send(ReadOnlySpan<byte> buffer)
- {
- if (!IsConnected)
- return 0;
- if (buffer.IsEmpty)
- return 0;
-
- long sent = Socket.Send(buffer, SocketFlags.None, out SocketError ec);
- if (sent > 0)
- {
-
- BytesSent += sent;
-
- OnSent(sent, BytesPending + BytesSending);
- }
-
- if (ec != SocketError.Success)
- {
- SendError(ec);
- Disconnect();
- }
- return sent;
- }
-
-
-
-
-
- public virtual long Send(string text) => Send(Encoding.UTF8.GetBytes(text));
-
-
-
-
-
- public virtual long Send(ReadOnlySpan<char> text) => Send(Encoding.UTF8.GetBytes(text.ToArray()));
-
-
-
-
-
- public virtual bool SendAsync(byte[] buffer) => SendAsync(buffer.AsSpan());
-
-
-
-
-
-
-
- public virtual bool SendAsync(byte[] buffer, long offset, long size) => SendAsync(buffer.AsSpan((int)offset, (int)size));
-
-
-
-
-
- public virtual bool SendAsync(ReadOnlySpan<byte> buffer)
- {
- if (!IsConnected)
- return false;
- if (buffer.IsEmpty)
- return true;
- lock (_sendLock)
- {
-
- if (((_sendBufferMain.Size + buffer.Length) > OptionSendBufferLimit) && (OptionSendBufferLimit > 0))
- {
- SendError(SocketError.NoBufferSpaceAvailable);
- return false;
- }
-
- _sendBufferMain.Append(buffer);
-
- BytesPending = _sendBufferMain.Size;
-
- if (_sending)
- return true;
- else
- _sending = true;
-
- TrySend();
- }
- return true;
- }
-
-
-
-
-
- public virtual bool SendAsync(string text) => SendAsync(Encoding.UTF8.GetBytes(text));
-
-
-
-
-
- public virtual bool SendAsync(ReadOnlySpan<char> text) => SendAsync(Encoding.UTF8.GetBytes(text.ToArray()));
-
-
-
-
-
- public virtual long Receive(byte[] buffer) { return Receive(buffer, 0, buffer.Length); }
-
-
-
-
-
-
-
- public virtual long Receive(byte[] buffer, long offset, long size)
- {
- if (!IsConnected)
- return 0;
- if (size == 0)
- return 0;
-
- long received = Socket.Receive(buffer, (int)offset, (int)size, SocketFlags.None, out SocketError ec);
- if (received > 0)
- {
-
- BytesReceived += received;
-
- OnReceived(buffer, 0, received);
- }
-
- if (ec != SocketError.Success)
- {
- SendError(ec);
- Disconnect();
- }
- return received;
- }
-
-
-
-
-
- public virtual string Receive(long size)
- {
- var buffer = new byte[size];
- var length = Receive(buffer);
- return Encoding.UTF8.GetString(buffer, 0, (int)length);
- }
-
-
-
- public virtual void ReceiveAsync()
- {
-
- TryReceive();
- }
-
-
-
- private void TryReceive()
- {
- if (_receiving)
- return;
- if (!IsConnected)
- return;
- bool process = true;
- while (process)
- {
- process = false;
- try
- {
-
- _receiving = true;
- _receiveEventArg.SetBuffer(_receiveBuffer.Data, 0, (int)_receiveBuffer.Capacity);
- if (!Socket.ReceiveAsync(_receiveEventArg))
- process = ProcessReceive(_receiveEventArg);
- }
- catch (ObjectDisposedException) {}
- }
- }
-
-
-
- private void TrySend()
- {
- if (!IsConnected)
- return;
- bool empty = false;
- bool process = true;
- while (process)
- {
- process = false;
- lock (_sendLock)
- {
-
- if (_sendBufferFlush.IsEmpty)
- {
-
- _sendBufferFlush = Interlocked.Exchange(ref _sendBufferMain, _sendBufferFlush);
- _sendBufferFlushOffset = 0;
-
- BytesPending = 0;
- BytesSending += _sendBufferFlush.Size;
-
- if (_sendBufferFlush.IsEmpty)
- {
-
- empty = true;
-
- _sending = false;
- }
- }
- else
- return;
- }
-
- if (empty)
- {
- OnEmpty();
- return;
- }
- try
- {
-
- _sendEventArg.SetBuffer(_sendBufferFlush.Data, (int)_sendBufferFlushOffset, (int)(_sendBufferFlush.Size - _sendBufferFlushOffset));
- if (!Socket.SendAsync(_sendEventArg))
- process = ProcessSend(_sendEventArg);
- }
- catch (ObjectDisposedException) {}
- }
- }
-
-
-
- private void ClearBuffers()
- {
- lock (_sendLock)
- {
-
- _sendBufferMain.Clear();
- _sendBufferFlush.Clear();
- _sendBufferFlushOffset= 0;
-
- BytesPending = 0;
- BytesSending = 0;
- }
- }
- #endregion
- #region IO processing
-
-
-
- private void OnAsyncCompleted(object sender, SocketAsyncEventArgs e)
- {
- if (IsSocketDisposed)
- return;
-
- switch (e.LastOperation)
- {
- case SocketAsyncOperation.Connect:
- ProcessConnect(e);
- break;
- case SocketAsyncOperation.Receive:
- if (ProcessReceive(e))
- TryReceive();
- break;
- case SocketAsyncOperation.Send:
- if (ProcessSend(e))
- TrySend();
- break;
- default:
- throw new ArgumentException("The last operation completed on the socket was not a receive or send");
- }
- }
-
-
-
- private void ProcessConnect(SocketAsyncEventArgs e)
- {
- IsConnecting = false;
- if (e.SocketError == SocketError.Success)
- {
-
- if (OptionKeepAlive)
- Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
- if (OptionTcpKeepAliveTime >= 0)
- Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, OptionTcpKeepAliveTime);
- if (OptionTcpKeepAliveInterval >= 0)
- Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, OptionTcpKeepAliveInterval);
- if (OptionTcpKeepAliveRetryCount >= 0)
- Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, OptionTcpKeepAliveRetryCount);
-
- if (OptionNoDelay)
- Socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, true);
-
- _receiveBuffer.Reserve(OptionReceiveBufferSize);
- _sendBufferMain.Reserve(OptionSendBufferSize);
- _sendBufferFlush.Reserve(OptionSendBufferSize);
-
- BytesPending = 0;
- BytesSending = 0;
- BytesSent = 0;
- BytesReceived = 0;
-
- IsConnected = true;
-
- TryReceive();
-
- if (IsSocketDisposed)
- return;
-
- OnConnected();
-
- if (_sendBufferMain.IsEmpty)
- OnEmpty();
- }
- else
- {
-
- SendError(e.SocketError);
- OnDisconnected();
- }
- }
-
-
-
- private bool ProcessReceive(SocketAsyncEventArgs e)
- {
- if (!IsConnected)
- return false;
- long size = e.BytesTransferred;
-
- if (size > 0)
- {
-
- BytesReceived += size;
-
- OnReceived(_receiveBuffer.Data, 0, size);
-
- if (_receiveBuffer.Capacity == size)
- {
-
- if (((2 * size) > OptionReceiveBufferLimit) && (OptionReceiveBufferLimit > 0))
- {
- SendError(SocketError.NoBufferSpaceAvailable);
- DisconnectAsync();
- return false;
- }
- _receiveBuffer.Reserve(2 * size);
- }
- }
- _receiving = false;
-
- if (e.SocketError == SocketError.Success)
- {
-
- if (size > 0)
- return true;
- else
- DisconnectAsync();
- }
- else
- {
- SendError(e.SocketError);
- DisconnectAsync();
- }
- return false;
- }
-
-
-
- private bool ProcessSend(SocketAsyncEventArgs e)
- {
- if (!IsConnected)
- return false;
- long size = e.BytesTransferred;
-
- if (size > 0)
- {
-
- BytesSending -= size;
- BytesSent += size;
-
- _sendBufferFlushOffset += size;
-
- if (_sendBufferFlushOffset == _sendBufferFlush.Size)
- {
-
- _sendBufferFlush.Clear();
- _sendBufferFlushOffset = 0;
- }
-
- OnSent(size, BytesPending + BytesSending);
- }
-
- if (e.SocketError == SocketError.Success)
- return true;
- else
- {
- SendError(e.SocketError);
- DisconnectAsync();
- return false;
- }
- }
- #endregion
- #region Session handlers
-
-
-
- protected virtual void OnConnecting() {}
-
-
-
- protected virtual void OnConnected() {}
-
-
-
- protected virtual void OnDisconnecting() {}
-
-
-
- protected virtual void OnDisconnected() {}
-
-
-
-
-
-
-
-
-
- protected virtual void OnReceived(byte[] buffer, long offset, long size) {}
-
-
-
-
-
-
-
-
-
- protected virtual void OnSent(long sent, long pending) {}
-
-
-
-
-
-
-
- protected virtual void OnEmpty() {}
-
-
-
-
- protected virtual void OnError(SocketError error) {}
- #endregion
- #region Error handling
-
-
-
-
- private void SendError(SocketError error)
- {
-
- if ((error == SocketError.ConnectionAborted) ||
- (error == SocketError.ConnectionRefused) ||
- (error == SocketError.ConnectionReset) ||
- (error == SocketError.OperationAborted) ||
- (error == SocketError.Shutdown))
- return;
- OnError(error);
- }
- #endregion
- #region IDisposable implementation
-
-
-
- public bool IsDisposed { get; private set; }
-
-
-
- public bool IsSocketDisposed { get; private set; } = true;
-
- public void Dispose()
- {
- Dispose(true);
- GC.SuppressFinalize(this);
- }
- protected virtual void Dispose(bool disposingManagedResources)
- {
-
-
-
-
-
-
-
-
-
-
-
- if (!IsDisposed)
- {
- if (disposingManagedResources)
- {
-
- DisconnectAsync();
- }
-
-
-
- IsDisposed = true;
- }
- }
- #endregion
- }
- }
|