EonaCat.Network/EonaCat.Network/System/Tcp/TcpClient.cs

132 lines
3.7 KiB
C#

using System;
using System.Net;
using System.Net.Sockets;
namespace EonaCat.Network
{
// This file is part of the EonaCat project(s) which is released under the Apache License.
// See the LICENSE file or go to https://EonaCat.com/License for full license details.
public class TcpClient
{
protected Socket clientSocket;
protected byte[] receiveBuffer = new byte[1024];
protected int BufferSize = 1024;
protected byte[] sendBuffer;
protected bool isSpitePackage;
protected int restPackage = -1;
protected int bufferIndex;
protected int maxSinglePacketSize = 1024;
public Func<byte[], byte[]> OnReceived;
public TcpClient(string serverIpAddress, int serverIpPort, Func<byte[], byte[]> OnReceived, IPType ipType = IPType.IPv4)
{
if (ipType == IPType.IPv6)
{
clientSocket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp);
}
else
{
clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
IPAddress ipAddress = IPAddress.Parse(serverIpAddress);
IPEndPoint ipEndpoint = new IPEndPoint(ipAddress, serverIpPort);
this.OnReceived = OnReceived;
clientSocket.BeginConnect(ipEndpoint, new AsyncCallback(ConnectAsynCallBack), clientSocket);
}
private void ConnectAsynCallBack(IAsyncResult ar)
{
Socket socketHandler = (Socket)ar.AsyncState;
try
{
socketHandler.EndConnect(ar);
socketHandler.BeginReceive(
receiveBuffer,
0,
BufferSize,
SocketFlags.None,
new AsyncCallback(ReceivedAsynCallBack),
socketHandler
);
}
catch (Exception e)
{
NetworkHelper.Logger.Error("[TcpClient] The remote computer rejected this request" + e.Message + "\n");
}
}
private void ReceivedAsynCallBack(IAsyncResult ar)
{
Socket socketHandler = (Socket)ar.AsyncState;
int byteLength = socketHandler.EndReceive(ar);
if (byteLength > 0)
{
if (OnReceived != null)
{
byte[] result = OnReceived(receiveBuffer);
if (result != null && result.Length > 0)
{
SendDataToServer(result);
}
}
}
socketHandler.BeginReceive(
receiveBuffer,
0,
BufferSize,
SocketFlags.None,
new AsyncCallback(ReceivedAsynCallBack),
socketHandler
);
}
private void SendAsynCallBack(IAsyncResult ar)
{
try
{
Socket socketHandler = (Socket)ar.AsyncState;
socketHandler.EndSend(ar);
}
catch (Exception e)
{
NetworkHelper.Logger.Exception(e);
}
}
public void SendDataToServer(byte[] msg)
{
if (!clientSocket.Connected)
{
NetworkHelper.Logger.Error("TcpClient is not connected, cannot send data");
return;
}
clientSocket.BeginSend(
msg,
0,
msg.Length,
0,
new AsyncCallback(SendAsynCallBack),
clientSocket
);
}
}
}