封装的socket类
class SocketClient
{
Socket skt;
IPEndPoint ipEndPoint;
public SocketClient(string ServerIpAddr, int Port)
{
IPAddress ipAddress = IPAddress.Parse(ServerIpAddr);
ipEndPoint = new IPEndPoint(ipAddress, Port);
skt = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
~SocketClient()
{
try
{
skt.Shutdown(SocketShutdown.Both);
skt.Close();
}
catch (Exception ex)
{
}
}
public bool Connect()
{
try
{
skt.Connect(ipEndPoint);
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool SendData(int SendBufferLen, byte[] SendBuffer)
{
try
{
int ret = skt.Send(SendBuffer, SendBufferLen, SocketFlags.None);
if (!skt.Connected)
{
return false;
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool SendData(string SendString)
{
try
{
byte[] SendBuffer = Encoding.Default.GetBytes(SendString);
int ret = skt.Send(SendBuffer);
if (!skt.Connected)
{
return false;
}
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool RecvData(byte[] RecvBuffer, ref int RecvBufferLen)
{
try
{
RecvBufferLen = skt.Receive(RecvBuffer);
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool RecvData(byte[] RecvBuffer, int BufferOffset, int NeedRecvLen, ref int RecvBufferLen)
{
try
{
RecvBufferLen = skt.Receive(RecvBuffer, BufferOffset, NeedRecvLen, SocketFlags.None);
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool RecvData(ref string RecvString)
{
try
{
byte[] RecvBuffer = new byte[1024 * 1024];
int RecvBufferLen = skt.Receive(RecvBuffer);
RecvString = Encoding.Default.GetString(RecvBuffer, 0, RecvBufferLen);
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool DisConnect()
{
try
{
if (skt != null)
{
skt.Shutdown(SocketShutdown.Both);
skt.Close();
}
return true;
}
catch (Exception ex)
{
return false;
}
}
}
调用socket实现socket连接
SocketClient sc = new SocketClient("127.0.0.1", 60000);
sc.Connect();//进行连接
//然后可以收发数据
实现socket监听服务
Socket acceptSocket = null;
Socket listenSocket = null;
/// <summary>
/// 监听请求
/// </summary>
/// <param name="port"></param>
public int Listen(IPAddress ip, int port)
{
listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
listenSocket.Bind(new IPEndPoint(ip, port));
listenSocket.Listen(100);
try
{
acceptSocket = listenSocket.Accept();
return 0;
}
catch (Exception ex)
{
DestroySocket(acceptSocket);
return -1;
}
}
/// <summary>
/// 销毁Socket对象
/// </summary>
/// <param name="socket"></param>
private static void DestroySocket(Socket socket)
{
if (socket.Connected)
{
socket.Shutdown(SocketShutdown.Both);
}
socket.Close();
}
//然后可以收发数据
acceptSocket.Send(data);
acceptSocket.Receive(data);