C# superSocket簡單示例

ba_wang_mao發表於2020-10-15

兩個端,一個服務端,一個客戶端。都是控制檯程式。

顯然地,服務端的要引用superSocket,但引用後編譯時候會提示,所以最終引用的內容如圖所示:

這裡寫圖片描述

superSocket內建了log4net,所以會有圖中所示。

然後上程式碼:

服務端:

using System;
using System.Linq;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Protocol;

namespace superSocketServer
{
    class Program
    {
        static AppServer appServer { get; set; }
        static void Main(string[] args)
        {
            appServer = new AppServer();


            //Setup the appServer
            if (!appServer.Setup(2012)) //Setup with listening port
            {
                Console.WriteLine("Failed to setup!");
                Console.ReadKey();
                return;
            }           

            //Try to start the appServer
            if (!appServer.Start())
            {
                Console.WriteLine("Failed to start!");
                Console.ReadKey();
                return;
            }


            Console.WriteLine("The server started successfully, press key 'q' to stop it!");

            //1.
            appServer.NewSessionConnected += new SessionHandler<AppSession>(appServer_NewSessionConnected);
            appServer.SessionClosed += appServer_NewSessionClosed;

            //2.
            appServer.NewRequestReceived += new RequestHandler<AppSession, StringRequestInfo>(appServer_NewRequestReceived);

            while (Console.ReadKey().KeyChar != 'q')
            {
                Console.WriteLine();
                continue;
            }

            //Stop the appServer
            appServer.Stop();

            Console.WriteLine("The server was stopped!");
            Console.ReadKey();
        }

        //1.
        static void appServer_NewSessionConnected(AppSession session)
        {
            Console.WriteLine($"服務端得到來自客戶端的連線成功");

            var count = appServer.GetAllSessions().Count();
            Console.WriteLine("~~" + count);
            session.Send("Welcome to SuperSocket Telnet Server");
        }

        static void appServer_NewSessionClosed(AppSession session, CloseReason aaa)
        {
            Console.WriteLine($"服務端 失去 來自客戶端的連線" + session.SessionID + aaa.ToString());
            var count = appServer.GetAllSessions().Count();
            Console.WriteLine(count);
        }

        //2.
        static void appServer_NewRequestReceived(AppSession session, StringRequestInfo requestInfo)
        {
            Console.WriteLine(requestInfo.Key);
            session.Send(requestInfo.Body);           
        }



    }
}

 客戶端

using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace superSocketClient
{
    class Program
    {
        static Socket socketClient { get; set; }
        static void Main(string[] args)
        {
            //建立例項
            socketClient = new Socket(SocketType.Stream, ProtocolType.Tcp);
            IPAddress ip = IPAddress.Parse("192.168.0.121");
            IPEndPoint point = new IPEndPoint(ip, 2012);
            //進行連線
            socketClient.Connect(point);


            //不停的接收伺服器端傳送的訊息
            Thread thread = new Thread(Recive);
            thread.IsBackground = true;
            thread.Start();


            不停的給伺服器傳送資料
            Thread thread2 = new Thread(Send);
            thread2.IsBackground = true;
            thread2.Start();

            Console.ReadKey();
        }

        /// <summary>
        /// 接收訊息
        /// </summary>
        /// <param name="o"></param>
        static void Recive()
        {
          //  為什麼用telnet客戶端可以,但這個就不行。
            while (true)
            {
                //獲取傳送過來的訊息
                byte[] buffer = new byte[1024 * 1024 * 2];
                var effective = socketClient.Receive(buffer);
                if (effective == 0)
                {
                    break;
                }
                var str = Encoding.UTF8.GetString(buffer, 0, effective);
                Console.WriteLine("來自伺服器 --- " + str);
                Thread.Sleep(2000);
            }
        }


        static void Send()
        {          
            int i = 0;
            int sum = 0;
            while (true)
            {
                i++;
                sum += i;
                var buffter = Encoding.UTF8.GetBytes($"ADD {sum} {sum + 1}" + "\r\n");
                var temp = socketClient.Send(buffter);
                Console.WriteLine(i);
                Thread.Sleep(1000);
            }

        }
    }
}

以上程式碼可直接執行,客戶端與伺服器可以互發訊息。
注意這只是一個基本應用,如果需要企業級的,高階一些的應用,則需要
自寫 Session、Server,需要繼承CommandBase和過載ExecuteCommand。如:

using System.Linq;
using SuperSocket.SocketBase;
using SuperSocket.SocketBase.Command;
using SuperSocket.SocketBase.Protocol;

namespace superSocketServer
{
    public class ADD : CommandBase<AppSession, StringRequestInfo>
    {
        public override void ExecuteCommand(AppSession session, StringRequestInfo requestInfo)
        {
            session.Send(requestInfo.Parameters.Select(p=>int.Parse(p)).Sum().ToString());
        }
    }
}

這樣的話,客戶端給伺服器發訊息,發諸如 “ ADD 3 4 \r\n” 這樣的字串給服務端,服務端就可以執行上面的這段程式碼,並且再返回給客戶端。

 

再然後,如果命令是很多的,也不能這樣寫死,就要使用C#的反射,動態地根據客戶端傳來的字串,然後呼叫服務端的響應函式。再返回給客戶端內容。
這裡只是說一個基本思路。
具體的格式,由客戶端與服務端具體約定。

完畢。

 

https://blog.csdn.net/festone000/article/details/80263126?utm_medium=distribute.pc_relevant_t0.none-task-blog-OPENSEARCH-1.channel_param&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-OPENSEARCH-1.channel_param

相關文章