Socket TCP_UDP简单实例

///

///Socket建立TCP链接

////

namespace Socket_TCP_服务端

{
    class Program
    {
        static void Main(string[] args)
        {
            //绑定IP和端口给当前程序
            Socket TCPServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipaddress = new IPAddress(new byte[] { 10, 246, 40, 205 });
            EndPoint point = new IPEndPoint(ipaddress, 7788);
            TCPServer.Bind(point);


            //开始监听
            TCPServer.Listen(100);
            Socket ClientSocket = TCPServer.Accept();//挂起不往下走 监听 知道有C来连接成功


            //Socket通信 
            //向客户端发送消息
            string message = "Hello 世界";
            byte[] mesData = Encoding.UTF8.GetBytes(message);
            ClientSocket.Send(mesData);


            //接收客户端消息
            byte[] receivedata = new byte[2048];
            int receiveLeng = ClientSocket.Receive(receivedata);
            string receivemessge = Encoding.UTF8.GetString(receivedata,0,receiveLeng);
            Console.WriteLine("从客户端接收到消息:" + receivemessge);
            Console.ReadKey();
        }
    }

}

namespace Socket_TCP_客户端_001
{
    class Program
    {
        static void Main(string[] args)
        {
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPAddress ipaddress = IPAddress.Parse("10.246.40.205");
            EndPoint point = new IPEndPoint(ipaddress, 7788);


            //建立连接
            tcpClient.Connect(point);


            //从服务器接收消息
            byte[] data = new byte[1024];
            int receiveLength = tcpClient.Receive(data);//接收data 返回值为接收到的长度
            string message = Encoding.UTF8.GetString(data, 0, receiveLength);
            Console.WriteLine(message);




            //向服务端发送消息
            string messageClient = Console.ReadLine();
            tcpClient.Send(Encoding.UTF8.GetBytes(messageClient));


            Console.ReadKey();
        }
    }
}


///标准接口

  1. /// <summary>  
  2. /// 连接使用tcp协议的服务端  
  3. /// </summary>  
  4. /// <param name="ip">服务端的ip</param>  
  5. /// <param name="port">服务端的端口号</param>  
  6. /// <returns></returns>  
  7. public static Socket ConnectServer(string ip, int port)  
  8. {  
  9.     Socket s = null;  
  10.     try  
  11.     {  
  12.         IPAddress ipAddress = IPAddress.Parse(ip);  
  13.         IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);  
  14.         s = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);  
  15.         s.Connect(ipEndPoint);  
  16.         if (s.Connected == false) s = null;  
  17.     }  
  18.     catch (Exception)  
  19.     {      
  20.     }  
  21.     return s;  
  22. }  
  1. /// <summary>  
  2. /// 连接使用tcp协议的服务端  
  3. /// </summary>  
  4. /// <param name="ip">服务端的ip</param>  
  5. /// <param name="port">服务端的端口号</param>  
  6. /// <returns></returns>  
  7. public static Socket ConnectServer(string ip, int port)  
  8. {  
  9.     Socket s = null;  
  10.     try  
  11.     {  
  12.         IPAddress ipAddress = IPAddress.Parse(ip);  
  13.         IPEndPoint ipEndPoint = new IPEndPoint(ipAddress, port);  
  14.         s = new Socket(ipEndPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp);  
  15.         s.Connect(ipEndPoint);  
  16.         if (s.Connected == false) s = null;  
  17.     }  
  18.     catch (Exception)  
  19.     {      
  20.     }  
  21.     return s;  
  22. }  
    1. /// <summary>  
    2.    /// 向远程主机发送数据  
    3.    /// </summary>  
    4.    /// <param name="socket">连接到远程主机的socket</param>  
    5.    /// <param name="buffer">待发送的字符串</param>  
    6.    /// <param name="outTime">发送数据的超时时间,单位是秒(为-1时,将一直等待直到有数据需要发送)</param>  
    7.    /// <returns>0:发送数据成功;-1:超时;-2:错误;-3:异常</returns>  
    8.    public static int SendData(Socket socket, string buffer, int outTime)  
    9.    {  
    10.        if (buffer == null || buffer.Length == 0)  
    11.        {  
    12.            throw new ArgumentException("buffer为null或则长度为0.");  
    13.        }  
    14.        return SendData(socket, System.Text.Encoding.Default.GetBytes(buffer), outTime);  
    15.    }  
    1. /// <summary>  
    2. /// 接收远程主机发送的数据  
    3. /// </summary>  
    4. /// <param name="socket">要接收数据且已经连接到远程主机的</param>  
    5. /// <param name="buffer">接收数据的缓冲区(需要接收的数据的长度,由 buffer 的长度决定)</param>  
    6. /// <param name="outTime">接收数据的超时时间,单位秒(指定为-1时,将一直等待直到有数据需要接收)</param>  
    7. /// <returns></returns>  
    8. public static int RecvData(Socket socket, byte[] buffer, int outTime)  
    9. {  
    10.     if (socket == null || socket.Connected == false)  
    11.     {  
    12.         throw new ArgumentException("socket为null,或者未连接到远程计算机");  
    13.     }  
    14.     if (buffer == null || buffer.Length == 0)  
    15.     {  
    16.         throw new ArgumentException("buffer为null ,或者长度为 0");  
    17.     }  
    18.   
    19.     buffer.Initialize();  
    20.     int left = buffer.Length;  
    21.     int curRcv = 0;  
    22.     int hasRecv=0;  
    23.     int flag = 0;  
    24.   
    25.     try  
    26.     {  
    27.         while (true)  
    28.         {  
    29.             if (socket.Poll(outTime * 1000, SelectMode.SelectRead) == true)  
    30.             {     
    31.                 // 已经有数据等待接收  
    32.                 curRcv = socket.Receive(buffer, hasRecv, left, SocketFlags.None);  
    33.                 left -= curRcv;  
    34.                 hasRecv += curRcv;  
    35.   
    36.                 // 数据已经全部接收   
    37.                 if (left == 0)  
    38.                 {                                      
    39.                     flag = 0;  
    40.                     break;  
    41.                 }  
    42.                 else  
    43.                 {  
    44.                     // 数据已经部分接收  
    45.                     if (curRcv > 0)  
    46.                     {                                  
    47.                         continue;  
    48.                     }  
    49.                     else  // 出现错误  
    50.                     {                                             
    51.                         flag = -2;  
    52.                         break;  
    53.                     }  
    54.                 }  
    55.             }  
    56.             else // 超时退出  
    57.             {                                                      
    58.                 flag = -1;  
    59.                 break;  
    60.             }  
    61.         }  
    62.     }  
    63.     catch (SocketException)  
    64.     {  
    65.         //Log  
    66.         flag = -3;  
    67.     }  
    68.     return flag;  
    69. }  

///

///

///Socket建立UDP链接

namespace Socket_UDP_Server
{
    class Program
    {
        public static Socket udpServer;
        static void Main(string[] args)
        {
            //创建UDP 绑定IP端口
            udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(new IPEndPoint(IPAddress.Parse("10.246.40.205"), 8899));


            //开启线程
            new Thread(ReceiveMessage) { IsBackground = true }.Start();




          
            Console.ReadKey();


        }
        /// <summary>
        ///  接收数据
        /// </summary>
        static void ReceiveMessage()
        {
            while (true)
            {


                EndPoint remoteEP = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = new byte[1024];
                int length = udpServer.ReceiveFrom(data, ref remoteEP);


                string message = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine("从IP:" + (remoteEP as IPEndPoint).Address + ":" + (remoteEP as IPEndPoint).Port + "收到数据:" + message);
            }


        }
    }
}


namespace Socket_UDP_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            //创建UDP
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);


            while (true)
            {


                //发送数据
                EndPoint serverPoint = new IPEndPoint(IPAddress.Parse("10.246.40.205"), 8899);
                string message = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(message);
                udpClient.SendTo(data, serverPoint);


                Console.ReadKey();


            }
        }
    }
}

猜你喜欢

转载自blog.csdn.net/cxihu/article/details/77049974