Giter VIP home page Giter VIP logo

Comments (4)

seayxu avatar seayxu commented on June 8, 2024

can you show your code?

from godsharp.socket.

LarryMai avatar LarryMai commented on June 8, 2024

Client Code
class Program
{
static void Main()
{

        int clientCount = 600;

        Console.WriteLine("Enter a key to start ");
        Console.Read();
        for (int i = 0; i < clientCount; ++i)
        {
            new Thread(
                () =>
                {
                    SocketClient client = new SocketClient("127.0.0.1", 7788);

                    client.OnData = (sender, data) =>
                    {
                        //get server data
                        string message = client.Encoding.GetString(data, 0, data.Length);
                        Console.SetCursorPosition(0, 0);
                        Console.WriteLine($"client received data from {sender.RemoteEndPoint.ToString()}: {message}");
                    };

                    try
                    {
                        client.Connect();
                        client.Start();

                        AddSocket(client);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"{ex}");
                    }
                })
            { IsBackground = true }.Start();

        }
        string msg = Console.ReadLine();

        while (msg.ToLower() != "q")
        {

            msg = Console.ReadLine();


            if (msg == "go")
            {

                int num1 = _socketCollection.Count;// new Random().Next(1, clientCount);
                Console.WriteLine($"Random num {num1} ..... ");

                List<string> ids = new List<string>();
                for (int i = 0; i < num1; ++i)
                {
                    int num = new Random().Next(0, _socketCollection.Count);

                    new Thread(
                        () =>
                        {
                            Thread.Sleep(new Random().Next(1000));

                            string input = $"[{num}] {GenerateRandomString(new Random().Next(50))}";
                            _socketCollection[num].Sender.Send(input);

                        })
                    { IsBackground = true }.Start();
                }
            }
        }


        Console.WriteLine("end ...");
        Console.ReadLine();
    }

    private const string CHARACTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

    /// <summary>
    /// Generates a random string.
    /// </summary>
    /// <param name="count">Length of the string.</param>
    /// <returns>Generated string</returns>
    public static string GenerateRandomString(int count = 8)
    {
        var random = new Random();

        return new string(
            Enumerable.Repeat(CHARACTERS, count)
                      .Select(s => s[random.Next(s.Length)])
                      .ToArray());


    }

}

from godsharp.socket.

LarryMai avatar LarryMai commented on June 8, 2024

Service Code :

class Program
{
///
public class SenderData
{
public TcpSender Sender { get; set; } = null;
public string Data { get; set; } = string.Empty;
}

    static ConcurrentDictionary<string, SenderData> _clientCollection = new ConcurrentDictionary<string, SenderData>();

    static string OutputLogPath =
        System.IO.Path.Combine(
            new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName,
            "Log");
    static void Main()
    {
        string logPath = System.IO.Path.Combine(
            new System.IO.FileInfo(System.Reflection.Assembly.GetExecutingAssembly().Location).DirectoryName, $"log_{DateTime.Now.ToString("HH_mm_ss")}.txt"
            );

        FileStream stream = new FileStream(logPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read);

        StreamWriter writer = new StreamWriter(stream);
       
        if (!Directory.Exists(OutputLogPath))
        {
            try
            {
                Directory.CreateDirectory(OutputLogPath);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex}");
            }
        }

        Random random = new Random();
        SocketServer server = new SocketServer()
        {
            OnConnected = async (sender) => 
            {

                Events.OnSocketConnectedEvent.Instance.Publish(sender);


             
        
            },
            OnClosed = (tcpSender) =>
            {       
                Events.OnSocketDisconnectedEvent.Instance.Publish(tcpSender);
            }
        };

        server.OnData = async (sender, data) =>
        {
            string message = server.Encoding.GetString(data, 0, data.Length);
            Events.OnSocketReceiveDataEvent.Instance.Publish(new Events.ReceivePacket() { Message = message, Sender = sender });
        };

        Events.OnSocketConnectedEvent.Instance.Subscribe(OnConnected
            ,  Prism.Events.ThreadOption.BackgroundThread
            );
        Events.OnSocketDisconnectedEvent.Instance.Subscribe(OnDisconnected
            ,Prism.Events.ThreadOption.BackgroundThread
            );
        Events.OnSocketReceiveDataEvent.Instance.Subscribe(OnDataReceived);
        server.Listen();
        server.Start();


       
        Console.ReadKey();
        writer.Close();
        stream.Close();
    }

    static object _lockObj = new object();

    static void OnConnected(TcpSender sender)
    {

        string key = sender.RemoteEndPoint.ToString();
        ThreadPool.QueueUserWorkItem(new WaitCallback(
           o =>
           {
               string p = o as string;
               if (p == null)
                   return;
               if (_clientCollection.ContainsKey(p))
                   _clientCollection[p] = new SenderData() { Data = string.Empty };
               else
                   _clientCollection.TryAdd(p, new SenderData() { Data = string.Empty });
               Console.WriteLine($"Count : {_clientCollection.Count}");
           }

           ), key);
    }
    static void OnDisconnected(TcpSender sender)
    {
        string key = sender.RemoteEndPoint.ToString();
        ThreadPool.QueueUserWorkItem(new WaitCallback(
          o =>
          {
              string p = o as string;
              if (p == null)
                  return;
              if (_clientCollection.ContainsKey(p))
              {
                  SenderData data = null;
                  _clientCollection.TryRemove(p, out data);
              }
              Console.WriteLine($"Client {p} is disconnected, totalCount : {_clientCollection.Count}");
          }

          ), key);
    }

    static void OnDataReceived (Events.ReceivePacket packet)
    {
        ThreadPool.QueueUserWorkItem(new WaitCallback(
            o =>
            {
                Events.ReceivePacket p = o as Events.ReceivePacket;
                if (p == null)
                    return;
                Console.WriteLine($"[{DateTime.Now.ToString("HH:mm:ss")}] {p.Sender.RemoteEndPoint}::{p.Message}");

            }), packet);
    }

}

from godsharp.socket.

LarryMai avatar LarryMai commented on June 8, 2024

My way to duplicate : I run the server.exe. Later, I run client.exe to create 600 sockets to the server and close the client.exe [several times]. The server will meet the OutOfIndex Exception.

from godsharp.socket.

Related Issues (16)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.