1. 程式人生 > >Socket程式設計的四種通訊方式

Socket程式設計的四種通訊方式

Socket程式設計

TCP和UDP區別

TCP協議中伺服器端和客戶端必須建立起連線才能收發資料 UDP協議中伺服器端和客戶端不需要建立連線,根據IP和埠號就能收發資料 1.基於連線和不連線 2.對系統資源的要求(TCP較多,UDP較少) 3.UDP結構簡單 4.流模式和資料報模式 5.TCP表示資料正確性,UDP可能丟包,TCP保證資料資料,UDP不保證 理解IP地址和埠號

1.有兩家公司,A公司和B公司,A公司有有小明a(經理),小紅a(職員),B公司有小明b(經理),小紅b(職員)。規定只有相同職位的人才可以交流 2.兩家公司有業務往來時,A公司的小明a(經理)和B公司的小明b(職員)交接,小紅a和小紅b交接。 3.此時,A公司和B公司相當於兩臺電腦,A公司和B公司相互郵寄東西的地址相當於電腦的IP地址,小明a和小明b的經理職位相當於兩臺電腦之間共有的軟體,小明a、小明b就是埠號。負責經理職位的相互通訊 4.A公司的小紅a想要找B公司的小紅b進行面談,小紅a要找到B公司的地址,再找到小紅b,才可以進行交流

TCP協議_建立伺服器端

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

namespace Socket_Tcp協議_伺服器端
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.建立Socket                                                      流模式  
            Socket tcpServe = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2.繫結IP跟埠號
            IPAddress ipAddress = new IPAddress(new byte[] {172,27,1,123 });//建立IP地址
            EndPoint point = new IPEndPoint(ipAddress,7788);//IPEndPoint是對IP+埠號加了一層封裝的類,7788是埠號
            tcpServe.Bind(point);//向作業系統申請一個可用的IP和埠號用來做通訊
            //3.開始監聽(等待客戶端做連線)
            Console.WriteLine("開始監聽了");
            tcpServe.Listen(100);//引數是最大連線數
            Socket clientSocket= tcpServe.Accept();//暫停當前執行緒,直到有一個客戶端連線過來,進行下面的程式碼
            //使用返回的Socket和客戶端做通訊
            Console.WriteLine("開始傳送訊息了");
            //4.傳送給客戶端訊息
            string message = "hello,歡迎你";
            byte[] data =Encoding.UTF8.GetBytes(message);//對字串做編碼,得到一個字串的位元組陣列
            clientSocket.Send(data);
            //5.接收來自客戶端的訊息
            byte[] b = new byte[1024];
            int length = clientSocket.Receive(b);
            string message3 = Encoding.UTF8.GetString(b,0,length);
            Console.WriteLine("接收一個從客戶端發來的訊息:"+message3);

            Console.ReadKey();

        }
    }
}

TCP協議_建立客戶端

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

namespace Socket_Tcp協議_客戶端
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.建立Socket
            Socket tcpClient = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            //2.發起建立連線的請求
            IPAddress add = IPAddress.Parse("172.27.1.123");//可以把一個字串的IP地址轉換為一個IPAddress的物件
            EndPoint point = new IPEndPoint(add, 7788);
            tcpClient.Connect(point);//通過IP:埠號定位到一個要連線的伺服器端
            //3.接收來自伺服器端的訊息
            byte[] data = new byte[1024];
            int length = tcpClient.Receive(data);//這裡傳遞一個byte陣列,實際上這個byte陣列用來接收資料
            //length返回值表示接收了多少資料
            string message = Encoding.UTF8.GetString(data,0,length);//只把接收到的資料進行轉化
            Console.WriteLine(message);
            //4.傳送給伺服器端訊息
            string message2 = Console.ReadLine();
            byte[] data1 = Encoding.UTF8.GetBytes(message2);
            tcpClient.Send(data1);

            Console.ReadKey();
        }
    }
}

UDP協議_建立伺服器端

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

namespace Sock
{
    /// <summary>
    /// udp伺服器端
    /// </summary>
    class Program
    {
        static Socket udpClient;
        static void Main(string[] args)
        {
            //1.建立Socket                                            資料報模式
            udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //2.繫結IP和埠號
            udpClient.Bind(new IPEndPoint(IPAddress.Parse("172.27.1.123"), 7788));
            //3.接收資料
            new Thread(ReceiveMessage) { IsBackground = true }.Start();

           // udpClient.Close();//關閉Socket
            Console.ReadKey();
        }
        static void ReceiveMessage()
        {
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = new byte[1024];
                int length = udpClient.ReceiveFrom(data, ref point);//這個方法會把資料的來源(IP:port)放到第二個引數裡面
                string message = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine("從IP:" + (point as IPEndPoint).Address.ToString() + ":" + (point as IPEndPoint).Port + "收到了資料:" + message);
            }
        }
    }
}

UDP協議_建立客戶端

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

namespace UDP_客戶端
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.建立Socket
            Socket udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            //2.向一個指定的ip地址和埠傳送資料
            while (true)
            {
                EndPoint point = new IPEndPoint(IPAddress.Parse("172.27.1.123"), 7788);
                string message = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(message);
                udpClient.SendTo(data, point);
            }
            
            udpClient.Close();
            Console.ReadKey();
        }
    }
}

TcpListener建立伺服器端

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

namespace Sock
{
    class Program
    {
       
        static void Main(string[] args)
        {
            //1.TcpClient對Socket進行了一層封裝,這個類裡面會自動去建立Socket物件
            TcpListener lister = new TcpListener(IPAddress.Parse("172.27.1.123"), 7788);
            //2.監聽
            lister.Start();
            //3.等待連線
            TcpClient tcp= lister.AcceptTcpClient();
            //4.取得客戶端傳過來的資料,建立網路流 
            NetworkStream stream = tcp.GetStream();//得到一個網路流,從這個網路流可以得到客戶端發過來的資料
            byte[] data = new byte[1024];
            while (true)
            {
                //0表示從陣列的哪個索引開始存放資料,1024表示最大的位元組讀取數
                int length = stream.Read(data, 0, 1024);//讀取資料
                string message = Encoding.UTF8.GetString(data, 0, length);
                Console.WriteLine("收到了訊息:" + message);
            }

            stream.Close();//網路流關閉
            tcp.Close();//連線關閉
            lister.Stop();//監聽關閉
            Console.ReadKey(); 
        }
        
    }
}

TcpClient建立客戶端

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

namespace UDP_客戶端
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.當我們建立TcpClient的時候,就會跟serve建立連線
            TcpClient tcpClient = new TcpClient("172.27.1.123", 7788);
            //2.建立網路流
            NetworkStream stream = tcpClient.GetStream();//通過網路流進行資料的交換 
            //3.傳送資料
            while (true)
            {
                string message = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(message);
                stream.Write(data, 0, data.Length);
            }
            stream.Close();
            tcpClient.Close();
            Console.ReadKey();
        }
    }
}

UdpClient建立伺服器端##

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

namespace Sock
{
    class Program
    { 
        static void Main(string[] args)
        {
            //1.建立udpClient
            UdpClient udpClient = new UdpClient(new IPEndPoint(IPAddress.Parse("172.27.1.123"),7788));
            //2.接收資料
            while (true)
            {
                IPEndPoint point = new IPEndPoint(IPAddress.Any, 0);
                byte[] data = udpClient.Receive(ref point);
                string message = Encoding.UTF8.GetString(data);
                Console.WriteLine("收到了訊息" + message);
            }
            udpClient.Close();
            Console.ReadKey(); 
        }
        
    }
}

UdpClient建立客戶端##

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

namespace UDP_客戶端
{
    class Program
    {
        static void Main(string[] args)
        {
            //1.建立UdpClient
            UdpClient udpClient = new UdpClient();
            //2.傳送資料
            while (true)
            {
                string message = Console.ReadLine();
                byte[] data = Encoding.UTF8.GetBytes(message);
                udpClient.Send(data, data.Length, new IPEndPoint(IPAddress.Parse("172.27.1.123"), 7788));
            }
            
            udpClient.Close();
            Console.ReadKey();
        }
    }
}