Odd performance when using C # asynchronous server

I am working on a web server in C # and I am running it on asynchronous socket calls. The strange thing is that for some reason, when you start loading pages, the third request is where the browser will not connect. He just keeps saying “Connecting ...” and never stops. If I remove the stop. and then it will update, it will boot again, but if I try again after that, it will do what it no longer loads on. And he continues in this cycle. I'm not quite sure what makes this happen.

The code seems to be hacked together from a few examples and some old code that I had. Any helpful tips will also be helpful.

Here is my little Listener class that handles everything

( pastished here . thought it would be easier to read this way)

using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using irek.Request;
using irek.Configuration;
namespace irek.Server
{
    public class Listener
    {
        private int port;
        private Socket server;
        private Byte[] data = new Byte[2048];
        static ManualResetEvent allDone = new ManualResetEvent(false);
        public Config config;

        public Listener(Config cfg)
        {
            port = int.Parse(cfg.Get("port"));
            config = cfg;
            ServicePointManager.DefaultConnectionLimit = 20;
        }

        public void Run()
        {
            server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint iep = new IPEndPoint(IPAddress.Any, port);
            server.Bind(iep);

            Console.WriteLine("Server Initialized.");
            server.Listen(5);
            Console.WriteLine("Listening...");
            while (true)
            {
                allDone.Reset();
                server.BeginAccept(new AsyncCallback(AcceptCon), server);
                allDone.WaitOne();
            }

        }

        private void AcceptCon(IAsyncResult iar)
        {
            allDone.Set();
            Socket s = (Socket)iar.AsyncState;
            Socket s2 = s.EndAccept(iar);
            SocketStateObject state = new SocketStateObject();
            state.workSocket = s2;
            s2.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), state);
        }

        private void Read(IAsyncResult iar)
        {
            try
            {
                SocketStateObject state = (SocketStateObject)iar.AsyncState;
                Socket s = state.workSocket;

                int read = s.EndReceive(iar);

                if (read > 0)
                {
                    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));

                    SocketStateObject nextState = new SocketStateObject();
                    nextState.workSocket = s;
                    s.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), nextState);
                }
                if (state.sb.Length > 1)
                {
                    string requestString = state.sb.ToString();
                    // HANDLE REQUEST HERE
                    byte[] answer = RequestHandler.Handle(requestString, ref config);
                    // Temporary response
                    /*
                    string resp = "<h1>It Works!</h1>";
                    string head = "HTTP/1.1 200 OK\r\nContent-Type: text/html;\r\nServer: irek\r\nContent-Length:"+resp.Length+"\r\n\r\n";
                    byte[] answer = Encoding.ASCII.GetBytes(head+resp);
                    // end temp.
                    */
                    state.workSocket.BeginSend(answer, 0, answer.Length, SocketFlags.None, new AsyncCallback(Send), s);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
                return;
            }
        }

        private void Send(IAsyncResult iar)
        {
            try
            {
                SocketStateObject state = (SocketStateObject)iar.AsyncState;
                int sent = state.workSocket.EndSend(iar);
                state.workSocket.Shutdown(SocketShutdown.Both);
                state.workSocket.Close();
            }
            catch (Exception)
            {

            }
            return;
        }
    }
}

And my SocketStateObject:

public class SocketStateObject
{
    public Socket workSocket = null;
    public const int BUFFER_SIZE = 1024;
    public byte[] buffer = new byte[BUFFER_SIZE];
    public StringBuilder sb = new StringBuilder();
}

** EDIT **

I updated the code with some suggestions from Chris Taylor.

+3
source share
3 answers

Just by looking at the code quickly, I suspect that you can stop registering your AsyncReads, because s.Available returns 0, I mean the following code

if (read > 0)
{
    state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));
    if (s.Available > 0) 
    { 
        s.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new   AsyncCallback(Read), state); 
        return; 
    } 
}

To confirm, change the above to the following

if (read > 0)
{
  state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, read));

  SocketStateObject nextState = new SocketStateObject();
  nextState.workSocket = s;
  s.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0, new AsyncCallback(Read), nextState);
}

This is not a complete code correction, but it will confirm if this is a problem. You need to make sure that you close sockets properly, etc.

Update I also noticed that you are sending a socket as a state in a BeginSend call.

 state.workSocket.BeginSend(answer, 0, answer.Length, SocketFlags.None, new AsyncCallback(Send), state.workSocket); 

Send AsyncState SocketStateObject

SocketStateObject state = (SocketStateObject)iar.AsyncState; 

InvalidCastExceptions, , catch. , , , , .

+1

, . Run() allDone, BeginAccept:

while (true)
{
     allDone.Reset();
     server.BeginAccept(new AsyncCallback(AcceptCon), server);
     allDone.WaitOne(); // <------
}

, AcceptConn :

private void AcceptCon(IAsyncResult iar)
{
    allDone.Set(); // <------

    Socket s = (Socket)iar.AsyncState;
    Socket s2 = s.EndAccept(iar);
    SocketStateObject state = new SocketStateObject();
    state.workSocket = s2;
    s2.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0,
        new AsyncCallback(Read), state);
}

The callback will be executed by a random thread from the pool, but allDone will be set before something is executed. It is possible that the Run () loop will start again in the first thread before completing work in AcceptCon. This will cause big problems.

You must set allDone after you have initialized (and especially after you have accessed items that are not associated with threads), for example:

private void AcceptCon(IAsyncResult iar)
{

    Socket s = (Socket)iar.AsyncState;
    Socket s2 = s.EndAccept(iar);
    SocketStateObject state = new SocketStateObject();
    state.workSocket = s2;

    allDone.Set(); // <------

    s2.BeginReceive(state.buffer, 0, SocketStateObject.BUFFER_SIZE, 0,
        new AsyncCallback(Read), state);

}
0
source

Source: https://habr.com/ru/post/1744590/


All Articles