天天看點

C# superSocket簡單示例

兩個端,一個服務端,一個用戶端。

都是控制台程式。

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

C# 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      

用戶端

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” 這樣的字元串給服務端,服務端就可以執行上面的這段代碼,并且再傳回給用戶端。

繼續閱讀