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?