Socket編程 (連接,發送消息) (Tcp、Udp) - Part1


Socket編程 (連接,發送消息) (Tcp、Udp) 

本篇文章主要實現Socket在Tcp\Udp協議下相互通訊的方式。(服務器端與客戶端的通訊)

  1.基於Tcp協議的Socket通訊類似於B/S架構,面向連接,但不同的是服務器端可以向客戶端主動推送消息。

  使用Tcp協議通訊需要具備以下幾個條件:

    (1).建立一個套接字(Socket)

    (2).綁定服務器端IP地址及端口號--服務器端

    (3).利用Listen()方法開啟監聽--服務器端

    (4).利用Accept()方法嘗試與客戶端建立一個連接--服務器端

    (5).利用Connect()方法與服務器建立連接--客戶端

    (5).利用Send()方法向建立連接的主機發送消息

    (6).利用Recive()方法接受來自建立連接的主機的消息(可靠連接)

    

 

  2.基於Udp協議是無連接模式通訊,占用資源少,響應速度快,延時低。至於可靠性,可通過應用層的控制來滿足。(不可靠連接)

    (1).建立一個套接字(Socket)

    (2).綁定服務器端IP地址及端口號--服務器端

    (3).通過SendTo()方法向指定主機發送消息(需提供主機IP地址及端口)

    (4).通過ReciveFrom()方法接收指定主機發送的消息(需提供主機IP地址及端口)

        

上代碼:由於個人代碼風格,習慣性將兩種方式寫在一起,讓用戶主動選擇Tcp\Udp協議通訊

服務器端:   

using System;
using System.Collections.Generic;
using System.Text;
#region 命名空間
using System.Net;
using System.Net.Sockets;
using System.Threading;
#endregion

namespace SocketServerConsole
{
    class Program
    {
        #region 控制台主函數
        /// <summary>
        /// 控制台主函數
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //主機IP
            IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("192.168.1.105"), 8686);
            Console.WriteLine("請選擇連接方式:");
            Console.WriteLine("A.Tcp");
            Console.WriteLine("B.Udp");
            ConsoleKey key;
            while (true)
            {
                key = Console.ReadKey(true).Key;
                if (key == ConsoleKey.A) TcpServer(serverIP);
                else if (key == ConsoleKey.B) UdpServer(serverIP);
                else
                {
                    Console.WriteLine("輸入有誤,請重新輸入:");
                    continue;
                }
                break;
            }
        }
        #endregion

        #region Tcp連接方式
        /// <summary>
        /// Tcp連接方式
        /// </summary>
        /// <param name="serverIP"></param>
        public static void TcpServer(IPEndPoint serverIP)
        {
            Console.WriteLine("客戶端Tcp連接模式");
            Socket tcpServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            tcpServer.Bind(serverIP);
            tcpServer.Listen(100);
            Console.WriteLine("開啟監聽...");
            new Thread(() =>
            {
                while (true)
                {
                    try
                    {
                        TcpRecive(tcpServer.Accept());
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出現異常:{0}", ex.Message));
                        break;
                    }
                }
            }).Start();
            Console.WriteLine("\n\n輸入\"Q\"鍵退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            tcpServer.Close();
        }

        public static void TcpRecive(Socket tcpClient)
        {
            new Thread(() =>
            {
                while (true)
                {
                    byte[] data = new byte[1024];
                    try
                    {
                        int length = tcpClient.Receive(data);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出現異常:{0}", ex.Message));
                        break;
                    }
                    Console.WriteLine(string.Format("收到消息:{0}", Encoding.UTF8.GetString(data)));
                    string sendMsg = "收到消息!";
                    tcpClient.Send(Encoding.UTF8.GetBytes(sendMsg));
                }
            }).Start();
        }
        #endregion

        #region Udp連接方式
        /// <summary>
        /// Udp連接方式
        /// </summary>
        /// <param name="serverIP"></param>
        public static void UdpServer(IPEndPoint serverIP)
        {
            Console.WriteLine("客戶端Udp模式");
            Socket udpServer = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            udpServer.Bind(serverIP);
            IPEndPoint ipep = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)ipep;
            new Thread(() =>
            {
                while (true)
                {
                    byte[] data = new byte[1024];
                    try
                    {
                        int length = udpServer.ReceiveFrom(data, ref Remote);//接受來自服務器的數據
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出現異常:{0}", ex.Message));
                        break;
                    }
                    Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                    string sendMsg = "收到消息!";
                    udpServer.SendTo(Encoding.UTF8.GetBytes(sendMsg), SocketFlags.None, Remote);
                }
            }).Start();
            Console.WriteLine("\n\n輸入\"Q\"鍵退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            udpServer.Close();
        }
        #endregion
    }
}

客戶端:

  

using System;
using System.Collections.Generic;
using System.Text;
#region 命名空間
using System.Net.Sockets;
using System.Net;
using System.Threading;
#endregion

namespace SocketClientConsole
{
    class Program
    {
        #region 控制台主函數
        /// <summary>
        /// 控制台主函數
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            //主機IP
            IPEndPoint serverIP = new IPEndPoint(IPAddress.Parse("192.168.1.77"), 8686);
            Console.WriteLine("請選擇連接方式:");
            Console.WriteLine("A.Tcp");
            Console.WriteLine("B.Udp");
            ConsoleKey key;
            while (true)
            {
                key = Console.ReadKey(true).Key;
                if (key == ConsoleKey.A) TcpServer(serverIP);
                else if (key == ConsoleKey.B) UdpClient(serverIP);
                else
                {
                    Console.WriteLine("輸入有誤,請重新輸入:");
                    continue;
                }
                break;
            }
        }
        #endregion

        #region Tcp連接方式
        /// <summary>
        /// Tcp連接方式
        /// </summary>
        /// <param name="serverIP"></param>
        public static void TcpServer(IPEndPoint serverIP)
        {
            Console.WriteLine("客戶端Tcp連接模式");
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                tcpClient.Connect(serverIP);
            }
            catch (SocketException e)
            {
                Console.WriteLine(string.Format("連接出錯:{0}", e.Message));
                Console.WriteLine("點擊任何鍵退出!");
                Console.ReadKey();
                return;
            }
            Console.WriteLine("客戶端:client-->server");
            string message = "我上線了...";
            tcpClient.Send(Encoding.UTF8.GetBytes(message));
            Console.WriteLine(string.Format("發送消息:{0}", message));
            new Thread(() =>
            {
                while (true)
                {
                    byte[] data = new byte[1024];
                    try
                    {
                        int length = tcpClient.Receive(data);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出現異常:{0}", ex.Message));
                        break;
                    }
                    Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                }
            }).Start();
            Console.WriteLine("\n\n輸入\"Q\"鍵退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            tcpClient.Close();
        }
        #endregion

        #region Udp連接方式
        /// <summary>
        /// Udp連接方式
        /// </summary>
        /// <param name="serverIP"></param>
        public static void UdpClient(IPEndPoint serverIP)
        {
            Console.WriteLine("客戶端Udp模式");
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            string message = "我上線了...";
            udpClient.SendTo(Encoding.UTF8.GetBytes(message), SocketFlags.None, serverIP);
            Console.WriteLine(string.Format("發送消息:{0}", message));
            IPEndPoint sender = new IPEndPoint(IPAddress.Any, 0);
            EndPoint Remote = (EndPoint)sender;
            new Thread(() =>
            {
                while (true)
                {
                    byte[] data = new byte[1024];
                    try
                    {
                        int length = udpClient.ReceiveFrom(data, ref Remote);//接受來自服務器的數據
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(string.Format("出現異常:{0}", ex.Message));
                        break;
                    }
                    Console.WriteLine(string.Format("{0} 收到消息:{1}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"), Encoding.UTF8.GetString(data)));
                }
            }).Start();
            Console.WriteLine("\n\n輸入\"Q\"鍵退出。");
            ConsoleKey key;
            do
            {
                key = Console.ReadKey(true).Key;
            } while (key != ConsoleKey.Q);
            udpClient.Close();
        }
        #endregion
    }
}

Tcp協議下通訊效果如下圖:

  客戶端:

  

  服務器端:

  

 

基於Udp協議下通訊效果如下圖:

  客戶端:

  

  服務器端:

  

 

總結:Tcp協議相對通訊來說相對可靠,信息不易丟失,Tcp協議發送消息,發送失敗時會重復發送消息等原因。所以對於要求通訊安全較高的程序來說,選擇Tcp協議的通訊相對合適。Upd協議通訊個人是比較推薦的,占用資源小,低延時,響應速度快。至於可靠性是可以通過一些應用層加以封裝控制得到相應的滿足。

 

附上源碼:Socket-Part1.zip

作者:曾慶雷
出處:http://www.cnblogs.com/zengqinglei
本頁版權歸作者和博客園所有,歡迎轉載,但未經作者同意必須保留此段聲明, 且在文章頁面明顯位置給出原文鏈接,否則保留追究法律責任的權利


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM