Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 770991
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T18:35:08+00:00 2026-05-14T18:35:08+00:00

I’m working on a web server in C# and I have it running on

  • 0

I’m working on a web server in C# and I have it running on Asynchronous socket calls. The weird thing is that for some reason, when you start loading pages, the 3rd request is where the browser won’t connect. It just keeps saying “Connecting…” and doesn’t ever stop. If I hit stop. and then refresh, it will load again, but if I try another time after that it does the thing where it doesn’t load again. And it continues in that cycle. I’m not really sure what is making it do that.

The code is kind of hacked together from a couple of examples and some old code I had. Any miscellaneous tips would be helpful as well.

Heres my little Listener class that handles everything

(pastied here. thought it might 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 have updated the code with some suggestions from Chris Taylor.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-14T18:35:08+00:00Added an answer on May 14, 2026 at 6:35 pm

    Just looking at the code quickly, I suspect that you might stop enquing your AsyncReads because s.Available is returning 0, I am refering to 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 the complete correction of the code, but it will confirm if this is the problem. You need to make sure that you are closing your sockets correctly etc.

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

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

    However, your callback Send is casting the AsyncState to SocketStateObject

    SocketStateObject state = (SocketStateObject)iar.AsyncState; 
    

    This will be raising InvalidCastExceptions which you are just hiding by adding the empty catch. I am sure others will agree, this is exceptionally bad practice having empty catches it hides so much info that you could be using to debug your problem.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

No related questions found

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.