CTcpClient类的源文件

CTcpClient类的源文件

转载:

http://blog.chiwudaili.com/detail.aspx?id=6b46e08d4c482f304e976a1081e40352

public class CTcpClient

{

private Socket ClientSocket { get; set; }

public CTcpClient()

{

ClientSocket = null;

}

public CTcpClient(Socket socket)

{

ClientSocket = socket;

}

public bool Start(int port = 8080, string ip = "127.0.0.1", int timeoutInSec = 10)

{

try

{

IPAddress ipA = IPAddress.Parse(ip);

ClientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

ClientSocket.SendTimeout = timeoutInSec * 1000;

ClientSocket.ReceiveTimeout = timeoutInSec * 1000;

ClientSocket.Connect(new IPEndPoint(ipA, port));

}

catch (Exception)

{

return false;

}

return true;

}

public int Receive(byte[] buffer, int offset, int size)

{

SocketError socketError = SocketError.Success;

int rel = ClientSocket.Receive(buffer, offset, size, SocketFlags.None, out socketError);

if (socketError == SocketError.Success)

{

return rel; 

}

return -1;

}

public int Send(byte[] buffer, int offset, int size)

{

SocketError socketError = SocketError.Success;

int rel = ClientSocket.Send(buffer, offset, size, SocketFlags.None, out socketError);

if (socketError == SocketError.Success)

{

return rel;

}

return -1;

}

public void Close()

{

if (ClientSocket!=null)

{

try

{

ClientSocket.Disconnect(false);

}

catch (Exception e)

{

}

try

{

ClientSocket.Dispose();

}

catch (Exception e)

{

}

try

{

ClientSocket.Close();

}

catch (Exception e)

{

}

ClientSocket = null;

}

}

}

猜你喜欢

转载自www.cnblogs.com/zj41342626/p/10053579.html