C#——Socket使用

1、Socket 连接

 //socket连接
 public void Connect(int receiveTimeout = 0, bool isTcp = true)
 {
     try
     {
         this.Socket = new Socket(AddressFamily.InterNetwork, isTcp? SocketType.Stream : SocketType.Dgram, isTcp ? ProtocolType.Tcp : ProtocolType.Udp);
         this.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, TimeOut);
         if (receiveTimeout > 0)
         {
             this.Socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, receiveTimeout);
         }

         IPAddress address = null;
         if (!IPAddress.TryParse(IPs, out address))
         {
             address = IPAddress.Parse("127.0.0.1");
         }

         IPEndPoint ip = new IPEndPoint(address, Ports);
         this.Socket.Connect(ip);
         connected = true;
     }
     catch (SocketException)
     {
         connected = false;
     }
     catch (Exception)
     {
         connected = false;
     }
 }

2、Socket 关闭连接

 //关闭socket连接
 public static void Close(Socket socket, ref bool connected)
 {
     try
     {
         if (socket != null)
         {
             connected = false;
             socket.Shutdown(SocketShutdown.Both);
             socket.Close();
         }
     }
     catch (SocketException)
     {
         connected = false;
     }
     catch (Exception)
     {
         connected = false;
     }
 }

3、Socket 读取数据

//socket数据读
public static byte[] Read(Socket socket, int length, ref bool connected)
{
    byte[] data = new byte[length];
    try
    {
        int nread = socket.Receive(data);
        if (nread == 0)
        {
            connected = false;
        }
        else
        {
            data = data.Take(nread).ToArray();
        }
    }
    catch
    {
        connected = false;
    }

    return data;
}

4、Socket 写数据

//socket 数据写
public static void Write(Socket socket, byte[] data, ref bool connected)
{
    try
    {
        socket.Send(data);
    }
    catch (SocketException)
    {
        connected = false;
    }
}

你可能感兴趣的:(C#,c#)