1. 程式人生 > 實用技巧 >C#網路程式設計(一)

C#網路程式設計(一)

這一次的部落格更新,主要內容是自己之前很小夥伴一起寫的一個仿QQ的程式。主要的知識就是 網路程式設計(僅支援區域網的通訊簡單的C/S架構資料庫(怎麼使用資料庫,因為我不是這個資料庫的設計者) 以及 桌面開發的基礎知識
網路通訊簡介
Socket還被稱作“套接字”,應用程式通常通過套接字向網路傳送請求或者應答網路請求。根據連線啟動的方式以及本地套接字要連線的目標,套接字之間的連線過程可以分為三個步驟:伺服器監聽,客戶端請求,連線確認。
從這幅經典的圖中,我們也可以基本瞭解網路應用程式的工作模式:

接下來我們就根據上圖的流程開始上程式碼:

  **二、建立客戶端和伺服器端**
  1、檢視本機ip地址
  Win+R:


輸入:cmd

輸入:ipconfig

得到ipv4的地址,滑鼠右鍵複製。
2、新建兩個桌面應用程式

3、執行程式碼程式碼:

//新增新的名稱空間
using System.Net.Sockets;
using System.Net;
using System.Threading;
//客戶端程式
namespace Cli
{
    class Program
    {
        
        //新建一個客戶端巢狀字
        static Socket client;

        //鍵入資料像伺服器端傳送
        static string sendStr;

        static void Main(string[] args)
        {
            //新建一個客戶端巢狀字
            client = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);

            //IP地址提供伺服器端的地址
            IPAddress ipAddress = IPAddress.Parse(<span style="color:red">伺服器端的IP地址</span>);

            //網路終端節點,埠可以任意,但是要大於1024
            IPEndPoint ipEndPoint = new IPEndPoint(ipAddress,5300);

            //用巢狀字去嘗試連線服務
            client.Connect(ipEndPoint);

            Console.WriteLine("請輸入您將向伺服器端傳送的訊息:");
            //鍵入將要傳送的資訊
            sendStr = Console.ReadLine();

            //設定一個大小為5M的位元組陣列用來存放帶傳送的資料
            byte[] sendMsg = new byte[1024 * 1024 * 5];
            //可以實現多次傳送資訊
            while (sendStr != "EXIT")
            {
                //將要傳送的字元轉化為位元組流
                sendMsg = Encoding.UTF8.GetBytes(sendStr);

                //用Send方法直接傳送
                client.Send(sendMsg);

                //重新開一個執行緒來持續接收從伺服器端的資料
                Thread receThread = new Thread(ReceMsg);
                //設定該執行緒會後臺執行緒
                receThread.IsBackground = true;
                //執行緒啟動
                receThread.Start();

                Console.WriteLine("請輸入您將向伺服器端傳送的訊息:");
                //鍵入將要傳送的資訊
                sendStr = Console.ReadLine();
            }

            Console.ReadLine();
        }
        
        //巢狀字接收訊息
        static void ReceMsg()
        {
            string receStr;
            byte[] receMsg = new byte[5 * 1024 * 1024];
            int length;
            while (true)
            {
                length = client.Receive(receMsg);
                //將接收到的流轉化為字串
                receStr = Encoding.UTF8.GetString(receMsg);

            }
            
        }

       
    }
    
}

using System.Threading;//執行緒名稱空間
using System.Net.Sockets;//巢狀字名稱空間
using System.Net;
//伺服器端
namespace Ser
{
    class Program
    {
        static Socket server;
        static void Main(string[] args)
        {
            //新建一個網路套接字
            //第一個引數代表使用IPv4網路地址
            //第二個引數代表網路資料傳輸時使用流形式
            //第三個引數代表使用的網路協議是TCP協議
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            //監聽任意客戶端
            IPAddress ipaddress = IPAddress.Any;

            //網路節點
            IPEndPoint ipendpoind = new IPEndPoint(ipaddress, 5300);

            //繫結該埠
            server.Bind(ipendpoind);

            //開始監聽——最大監聽佇列
            server.Listen(36);

            Console.WriteLine("開始監聽");

            //重新開一個執行緒監聽客戶端巢狀字
            Thread receThread = new Thread(ListenSocket);
            //設定該執行緒會後臺執行緒
            receThread.IsBackground = true;
            //執行緒啟動
            receThread.Start();

            Console.ReadLine();

        }

        //監聽客戶端巢狀字
        static void ListenSocket()
        {
            while (true)
            {
                Socket client = server.Accept();

                Console.WriteLine("客戶端:" + client.RemoteEndPoint.ToString() + "連線成功!");

                //重新開一個執行緒來持續接收從伺服器端的資料
                Thread receThread = new Thread(ReceMsg);
                //設定該執行緒會後臺執行緒
                receThread.IsBackground = true;
                //執行緒啟動
                receThread.Start(client);
            }
        }
        //巢狀字接收訊息
        static void ReceMsg(object obj)
        {
            
            string receStr;
            byte[] receMsg = new byte[5 * 1024 * 1024];
            int length;
            while (true)
            {
                //強制轉換
                Socket client = obj as Socket;

                length = client.Receive(receMsg);

                //將接收到的流轉化為字串
                receStr = Encoding.UTF8.GetString(receMsg,0,length);

                Console.WriteLine("客戶端:"+client.RemoteEndPoint.ToString()+"發來訊息:"+receStr);

            }

        } 
       
    }
}

4、執行結果: