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 4551756
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 21, 20262026-05-21T16:40:51+00:00 2026-05-21T16:40:51+00:00

hey all, I have made a socket server in C# for a flash game

  • 0

hey all,
I have made a socket server in C# for a flash game that I am developing, I got the code from somewhere and I am a beginner in c# and .net development . It works fine in practice when connections are made and the server functions correctly. Get 2 concurrent connections at the same time and we have a problem.

here is the basic aspects of the socket server below: (alot taken out for obvious reasons)

how can I alter this so that it can handle concurrent connections? Should I be threading each response?

Thanks


class TcpSock
{
int tcpIndx = 0;
int tcpByte = 0;

    byte[] tcpRecv = new byte[1024];

    ////////////////////////////////////////
    public Socket tcpSock;
    ////////////////////////////////////////

    public int Recv(ref string tcpRead)
    {
        tcpByte = tcpSock.Available;
        if (tcpByte > tcpRecv.Length - tcpIndx)
            tcpByte = tcpRecv.Length - tcpIndx;

        tcpByte = tcpSock.Receive(tcpRecv, tcpIndx, tcpByte,
            SocketFlags.Partial);
        tcpRead = Encoding.ASCII.GetString
            (tcpRecv, tcpIndx, tcpByte);
        tcpIndx += tcpByte;
        return tcpRead.Length;
    }

    public int RecvLn(ref string tcpRead)
    {
        tcpRead = Encoding.ASCII.GetString
            (tcpRecv, 0, tcpIndx);
        tcpIndx = 0;
        return tcpRead.Length;
    }

    public int Send(string tcpWrite)
    {
        return tcpSock.Send(Encoding.ASCII.GetBytes(tcpWrite));
    }

    public int SendLn(string tcpWrite)
    {
        return tcpSock.Send(Encoding.ASCII.GetBytes(tcpWrite + "\r\n"));
    }


}


[STAThread]
static void Main()
{

        Thread Server1 = new Thread(RunServer);
        Server1.Start();

    }

    static void RunServer()
    {


        ///class IPHostEntry : Stores information about the Host and is required
        ///for IPEndPoint.
        ///class IPEndPoint  : Stores information about the Host IP Address and
        ///the Port number.
        ///class TcpSock     : Invokes the constructor and creates an instance.
        ///class ArrayList   : Stores a dynamic array of Client TcpSock objects.

        IPHostEntry Iphe = Dns.Resolve(Dns.GetHostName());
        IPEndPoint Ipep = new IPEndPoint(Iphe.AddressList[0], 4444);
        Socket Server = new Socket(Ipep.Address.AddressFamily,SocketType.Stream, ProtocolType.Tcp);


        ///Initialize
        ///Capacity : Maximux number of clients able to connect.
        ///Blocking : Determines if the Server TcpSock will stop code execution
        ///to receive data from the Client TcpSock.
        ///Bind     : Binds the Server TcpSock to the Host IP Address and the Port Number.
        ///Listen   : Begin listening to the Port; it is now ready to accept connections.

        ArrayList Client = new ArrayList();

        string[,] Users = new string[1000,9];

        string rln = null;

        string[] Data;


        Client.Capacity = 1000;



        Server.Blocking = false;
        Server.Bind(Ipep);
        Server.Listen(32);

        Console.WriteLine("Server 1 {0}: listening to port {1}", Dns.GetHostName(), Ipep.Port);

        ////////////////////////////////////////////////////////////////////////////////////////////
        ///Main loop
        ///1. Poll the Server TcpSock; if true then accept the new connection.
        ///2. Poll the Client TcpSock; if true then receive data from Clients.

        while (true)
        {
            //Accept - new connection

            #region new connection
            if (Server.Poll(0, SelectMode.SelectRead))
            {
                int i = Client.Add(new TcpSock());



                ((TcpSock)Client[i]).tcpSock = Server.Accept();
                Console.WriteLine("Client " + i + " connected.");


                Users[i, 0] = i.ToString();


            }
            #endregion 

            for (int i = 0; i < Client.Count; i++)
            {
                //check for incoming data
                if (((TcpSock)Client[i]).tcpSock.Poll(0, SelectMode.SelectRead))
                {
                    //receive incoming data
                    if (((TcpSock)Client[i]).Recv(ref rln) > 0)
                    {
                        Console.WriteLine(rln.ToString());
                        Data = rln.Split('|');

                        // 1) initial connection
                        #region InitialConnection

                        if (Data[0] == "0000")

                        {

                        }



                   }
               }
         }
    }

}

  • 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-21T16:40:51+00:00Added an answer on May 21, 2026 at 4:40 pm
    using System;
    using System.IO;
    using System.Net;
    using System.Net.Sockets;
    using System.Text;
    
    public static partial class TcpServer
    {
        public static void Main()
        {
            // Setup listener on "localhost" port 12000
            IPAddress ipAddr = Dns.GetHostEntry("localhost").AddressList[0];
            TcpListener server = new TcpListener(ipAddr, 12000);
            server.Start(); // Network driver can now allow incoming requests 
    
            // Accept up to 1 client per CPU simultaneously
            Int32 numConcurrentClients = Environment.ProcessorCount;
    
            for (Int32 n = 0; n 
    
    
        private static Byte[] ProcessData(Byte[] inputData)
        {
            String inputString = Encoding.UTF8.GetString(inputData, 1, inputData[0]);
            String outputString = inputString.ToUpperInvariant();
    
            Console.WriteLine("Input={0}", inputString);
            Console.WriteLine("   Output={0}", outputString);
            Console.WriteLine();
    
            Byte[] outputStringBytes = Encoding.UTF8.GetBytes(outputString);
            Byte[] outputData = new Byte[1 + outputStringBytes.Length];
            outputData[0] = (Byte)outputStringBytes.Length;
            Array.Copy(outputStringBytes, 0, outputData, 1, outputStringBytes.Length);
            return outputData;
        }
    }
    
    public static partial class TcpServer
    {
        private sealed class ClientConnectionApm
        {
            private TcpListener m_server;
            private TcpClient m_client;
            private Stream m_stream;
            private Byte[] m_inputData = new Byte[1];
            private Byte m_bytesReadSoFar = 0;
    
            public ClientConnectionApm(TcpListener server)
            {
                m_server = server;
                m_server.BeginAcceptTcpClient(AcceptCompleted, null);
            }
    
            private void AcceptCompleted(IAsyncResult ar)
            {
                // Connect to this client
                m_client = m_server.EndAcceptTcpClient(ar);
    
                // Accept another client
                new ClientConnectionApm(m_server);
    
                // Start processing this client
                m_stream = m_client.GetStream();
                // Read 1 byte from client which contains length of additional data
                m_stream.BeginRead(m_inputData, 0, 1, ReadLengthCompleted, null);
            }
    
            private void ReadLengthCompleted(IAsyncResult result)
            {
                // If client closed connection; abandon this client request
                if (m_stream.EndRead(result) == 0) { m_client.Close(); return; }
    
                // Start to read 'length' bytes of data from client
                Int32 dataLength = m_inputData[0];
                Array.Resize(ref m_inputData, 1 + dataLength);
                m_stream.BeginRead(m_inputData, 1, dataLength, ReadDataCompleted, null);
            }
    

    private void ReadDataCompleted(IAsyncResult ar)
    {
    // Get number of bytes read from client
    Int32 numBytesReadThisTime = m_stream.EndRead(ar);

    // If client closed connection; abandon this client request
    if (numBytesReadThisTime == 0) { m_client.Close(); return; }

    // Continue to read bytes from client until all bytes are in
    m_bytesReadSoFar += (Byte)numBytesReadThisTime;
    if (m_bytesReadSoFar

    private void WriteDataCompleted(IAsyncResult ar)
    {
    // After result is written to client, close the connection
    m_stream.EndWrite(ar);
    m_client.Close();
    }
    }
    }

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

Sidebar

Related Questions

Hey all. I have a server written in java using the ServerSocket and Socket
Hey all - I have an app where I'm authenticating the user. They pass
Hey all, I have something of an interesting requirement for my project. I need
Hey all, my Computational Science course this semester is entirely in Java. I was
Hey all. Newbie question time. I'm trying to setup JMXQuery to connect to my
Hey all. We're sending quite a few emails (around 23k) using IIS6 SMTP service
Hey all, I'm pulling my hair out on this one. I've checked all my
Hey everyone, I'm using Virtual PC and working with a virtual hard disk (*.vhd)
Hey so what I want to do is snag the content for the first
Hey, I'm using Levenshteins algorithm to get distance between source and target string. also

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.