0
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace sockasyncsrv
{
    class Program
    {
        static void Main(string[] args)
        {
            RunAsyncSocketServer().Wait();
        }

        static async Task RunAsyncSocketServer()
        { 
            int MAX_SIZE = 1024; 

            Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


            IPEndPoint ep = new IPEndPoint(IPAddress.Any, 7000);
            sock.Bind(ep);

            sock.Listen(100);

            while (true)
            {
                Socket clientSock = await Task.Factory.FromAsync(sock.BeginAccept, sock.EndAccept, null);

                var buff = new byte[MAX_SIZE];

                int nCount = await Task.Factory.FromAsync<int>(
                           clientSock.BeginReceive(buff, 0, buff.Length, SocketFlags.None, null, clientSock),
                           clientSock.EndReceive);

                if (nCount > 0)
                {
                    string msg = Encoding.ASCII.GetString(buff, 0, nCount);
                    Console.WriteLine(msg);

                    await Task.Factory.FromAsync(
                            clientSock.BeginSend(buff, 0, buff.Length, SocketFlags.None, null, clientSock),
                            clientSock.EndSend);
                }

                clientSock.Close();
            }
        }
    }
}

After a client connect my server, then I want to continue to receive message from the connected client. So I used 'while(true)' above 'if(nCount>0)', then it is impossible to accept another clients. How to get multi-client?

1
  • 3
    Short answer: Threading. You need to spawn a thread for each client and keep the ServerSocket listening and accepting connections while the spawned threads handle communication with each Client Socket concurrently. Commented Jan 24, 2018 at 9:13

1 Answer 1

2

You need multiple sockets for multiple connections. A Soket is designet to handle one connection. You can Create a new Socket that waits for a connectino once the first one has a connection.(wen the thread enters the while (true) loop)

You could also have multiple sockets listen at the same time. Maby on a different port? Soemthing like this.

    static async Task RunAsyncSocketServer(int port)
    {
        int MAX_SIZE = 1024;

        Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);


        IPEndPoint ep = new IPEndPoint(IPAddress.Any, port);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.