1. 程式人生 > >C# FrameworkAPI之Socket通訊

C# FrameworkAPI之Socket通訊

服務端:
1:建立一個socket的物件

Socket socketserver=new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

第一個引數是指定socket物件使用的定址方案,即IPV4或IPV6;
第二個引數socket物件的套接字的型別,此處stream是表示流式套接字
第三個引數socket物件支援的協議,TCP協議或UDP協議。
這三個引數一般初期使用上面的就OK了,到了後期對socket通訊熟悉了再來看其它引數的功能及作用。

2:使用指定的埠號和伺服器的ip地址初始化System.Net.IPEndPoint類的例項

IPEndPoint endpoint=new IPEndPoint(ipaddress, port);

3:用socket對像socketserver的Bind()方法繫結IPEndPoint;

socketserver.Bind(endpoint);

4:用socket對像socketserver的Listen()方法開始監聽;

socketwatch.Listen(20);//此處是讓伺服器可以監聽20個客戶端的連線。

5:接受到客戶端的連線,用socket對像的Accept()方法建立新的socket對像用於和請求的客戶端進行通訊;

SocketsocConnection = socketwatch.Accept();//socConnection 就是伺服器監聽到的客戶端連線的套接字,伺服器就可以通過socConnection 和該連線的客戶端進行通訊。

6;此處就可以使用socConnection 進行通訊Receive()和Send();
7:通訊結束後一定記得關閉socket,close()方法;

程式碼如下:

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

namespace SocketTestServer
{
    class Program
    {
        private static byte[] result = new byte[1024];
        private static int myProt = 2000;//埠
        static Socket serverSocket;
        static void Main(string[] args)
        {
            //伺服器IP地址
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); ;
            serverSocket.Bind(new IPEndPoint(ip, myProt));//繫結IP地址:埠 
            serverSocket.Listen(10);//設定最多10個排隊連線請求  
            Console.WriteLine("啟動監聽{0}成功", serverSocket.LocalEndPoint.ToString());

            //通過clientsocket傳送資料
            Thread myThread = new Thread(ListenClientConnect);
            myThread.Start();
            Console.ReadLine();
        }


        //監聽客戶端連線  
        private static void ListenClientConnect()
        {
            while (true)
            {
                Socket clientsocket = serverSocket.Accept();
                clientsocket.Send(Encoding.ASCII.GetBytes("server say hello"));
                Thread receiveThread = new Thread(ReceiveMessage);
                receiveThread.Start(clientsocket);
            }
        }

        //接收訊息
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;
            while (true)
            {
                try
                {
                    //通過clientsocket接收資料
                    int num = myClientSocket.Receive(result);
                    Console.WriteLine("接收客戶端{0}訊息{1}", myClientSocket.RemoteEndPoint.ToString(), Encoding.ASCII.GetString(result, 0, num));

                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                    myClientSocket.Shutdown(SocketShutdown.Both);
                    myClientSocket.Close();
                    break;
                }
            }
        }

    }
}

客戶端:
1:建立一個socket的物件socketclient(和伺服器一樣)
2:使用指定的埠號和伺服器的ip地址初始化System.Net.IPEndPoint類的例項(和伺服器一樣)
3:用socket對像socketclient的Connect()方法以上面建立的IPEndPoint對像做為引數,向伺服器發出連線請求;其中Connect的引數就是第二步IPEndPoint的例項
4:連線成功後,就可以進行通訊(Receive()和Send())
5:通訊結束後一定記得關閉socket,close()方法;

程式碼如下:

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

namespace SocketTestClient
{
    class Program
    {
        private static byte[] result = new byte[1024];
        static void Main(string[] args)
        {
             //繫結伺服器IP地址
            IPAddress ip = IPAddress.Parse("127.0.0.1");
            Socket clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
 
            try
            {
                clientSocket.Connect(new IPEndPoint(ip, 2000));
                Console.WriteLine("連線伺服器成功");
 
            }
            catch
            {
                Console.WriteLine("連線伺服器失敗,請按回車鍵退出");
                return;
            }
 
            //通過clientSocket接受資料
            int num = clientSocket.Receive(result);
            Console.WriteLine("接收伺服器訊息:{0}", Encoding.ASCII.GetString(result, 0, num));    
 
 
            //通過 clientSocket 傳送資料    
           for (int i = 0; i < 10; i++)    
            {    
                try    
               {    
                   Thread.Sleep(1000);    //等待1秒鐘    
                    string sendMessage = "client send Message Hellp" + DateTime.Now;    
                    clientSocket.Send(Encoding.ASCII.GetBytes(sendMessage));    
                    Console.WriteLine("向伺服器傳送訊息:{0}" + sendMessage);    
                }    
               catch    
                {    
                    clientSocket.Shutdown(SocketShutdown.Both);    
                    clientSocket.Close();    
                    break;    
                }    
            }    
            Console.WriteLine("傳送完畢,按回車鍵退出");    
           Console.ReadLine();   
        }
    }
}

這只是通訊時伺服器和客戶端的最簡單的流程。