NetCore3.1 TCP服務之BeetleX

天才卧龙發表於2024-12-03

十年河東,十年河西,莫欺少年窮

學無止境,精益求精

1、安裝包

2、server端

using BeetleX;
using BeetleX.EventArgs;
using System;

namespace BTcp
{
    
    class Program : BeetleX.ServerHandlerBase
    {
        static int Number = 0;
        private static BeetleX.IServer mServer;
        static void Main(string[] args)
        {
            mServer = SocketFactory.CreateTcpServer<Program>();
            mServer.Options.DefaultListen.Port = 9090;
            mServer.Options.DefaultListen.Host = "127.0.0.1";
            mServer.Open();
            Console.WriteLine(mServer.Status);
            Console.Read();
        }
        protected override void OnLogToConsole(IServer server, ServerLogEventArgs e)
        {

            Console.WriteLine($"{DateTime.Now}\t{e.Type}\t{e.Session?.RemoteEndPoint} {e.Message}");
        }

        public override void SessionReceive(IServer server, SessionReceiveEventArgs e)
        {
            base.SessionReceive(server, e);
            var stream = e.Stream.ToPipeStream();
            if (stream.TryReadLine(out string line))
            {
                Number++;
                Console.WriteLine(line+ ""+Number);
                stream.WriteLine($"{DateTime.Now}");
                e.Stream.Flush();
            }
        }
    }
}

3、客戶端

using BeetleX;
using BeetleX.Clients;
using System;
using System.Net.Sockets;
using System.Threading.Tasks;

namespace BTcpClient
{
    class Program
    {
        static void Main(string[] args)
        {
            Parallel.For(0, 10000, i =>
            {
                AsyncTcpClient client = SocketFactory.CreateClient<AsyncTcpClient>("127.0.0.1", 9090);
                client.ClientError = (o, e) =>
                {
                    Console.WriteLine("client error {0}@{1}", e.Message, e.Error);
                };
                client.DataReceive = (o, e) =>
                {
                    Console.WriteLine(e.Stream.ToPipeStream().ReadLine());
                };
                var pipestream = client.Stream.ToPipeStream();
                pipestream.WriteLine("hello BeetleX");
                client.Stream.Flush();
            });
          
            Console.Read();
        }
    }
}

4、測試結果

模擬短時間內,建立10000個連結

相關文章