1. 程式人生 > >C#Socket通訊基礎(同步Socket通訊UDP)

C#Socket通訊基礎(同步Socket通訊UDP)

一、UDP通訊原理

UDP協議使用無連線的套接字,因此不需要再網路裝置之間傳送連線資訊,但是必須用Bind方法繫結到一個本地地址/埠上。

①建立套接字

②繫結IP地址和埠作為伺服器端

③直接使用SendTo/ReceiveFrom來執行操作

注意:同步Socket(UDP)通訊存在缺點:只能單向接收或者傳送資料

二、編寫對應的控制檯應用程式的伺服器端與客戶端指令碼

<1>伺服器端(資訊傳送端)指令碼如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Test_Socket_UDP
{
    class UDPSending
    {

        static void Main(string[] args)
        {
            UDPSending obj = new UDPSending();
            Console.WriteLine("---傳送端---");
            obj.SocketUDPSending();
        }

        public void SocketUDPSending()
        {
            //定義傳送位元組區
            byte[] byteArray = new byte[100];

            //定義網路地址
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 1000);
            Socket socketClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            EndPoint ep = (EndPoint)iep;

            //傳送資料
            Console.WriteLine("請輸入傳送的資料");
            while (true)
            {
                string strMsg = Console.ReadLine();
                //位元組轉換
                byteArray = Encoding.Default.GetBytes(strMsg);
                socketClient.SendTo(byteArray, ep);
                if (strMsg == "exit")
                {
                    break;
                }

            }
            socketClient.Shutdown(SocketShutdown.Both);
            socketClient.Close();
        }

    }//Class_end
}

<2>客戶端端(資訊接收端)指令碼如下: 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace Test_Socket_UDPAccept
{
    class UDPAccept
    {
        static void Main(string[] args)
        {
            UDPAccept obj = new UDPAccept();
            Console.WriteLine("---接收端---");
            obj.SocketUDPAccept();
            
        }

        //接收端
        private void SocketUDPAccept()
        {
            //定義接收的資料區
            byte[] byteArray = new byte[100];

            //定義網路地址
            IPEndPoint iep = new IPEndPoint(IPAddress.Parse("127.0.0.1"),1000);
            Socket socketServer = new Socket(AddressFamily.InterNetwork,SocketType.Dgram,ProtocolType.Udp);
            socketServer.Bind(iep);//地址繫結伺服器端
            EndPoint ep = (EndPoint)iep;

            //接受資料
            while (true)
            {
                int intReceiveLength = socketServer.ReceiveFrom(byteArray,ref ep);
                string strReceiveStr = Encoding.Default.GetString(byteArray,0,intReceiveLength);
                Console.WriteLine(strReceiveStr);
            }


        }

    }//class_end
}

三、執行程式 ,測試如下

注:本內容來自《Unity3D/2D遊戲開發從0到1》28章