I am working on a client / server application in C # and I need to get asynchronous sockets to work so that I can handle multiple connections at once. Technically, it works the way it does now, but I get it OutOfMemoryExceptionafter about 3 minutes of work. MSDN says use WaitHandlerto execute WaitOne()after socket.BeginAccept(), but it really prevents me from doing this. When I try to do this in code, it says that it WaitHandleris an abstract class or interface, and I cannot create it. I thought that perhaps Id would try a static link, but it has no method WaitOne(), just WaitAll()andWaitAny(). The main problem is that in the documents it does not give a complete piece of code, so you cannot see what happens to their wait handler. its just a variable called allDone, which also has a method Reset()in the fragment that waithandler does not have.
After searching in my documents, I found some related things in the AutoResetEventnamespace Threading. He has a method WaitOne()and a Reset(). So I tried it around while(true) { ... socket.BeginAccept( ... ); ... }. Unfortunately, this forces us to use only one connection at a time. Therefore, I’m not quite sure where to go. Here is my code:
class ServerRunner
{
private Byte[] data = new Byte[2048];
private int size = 2048;
private Socket server;
static AutoResetEvent allDone = new AutoResetEvent(false);
public ServerRunner()
{
server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 33333);
server.Bind(iep);
Console.WriteLine("Server initialized..");
}
public void Run()
{
server.Listen(100);
Console.WriteLine("Listening...");
while (true)
{
server.BeginAccept(new AsyncCallback(AcceptCon), server);
}
}
void AcceptCon(IAsyncResult iar)
{
Socket oldserver = (Socket)iar.AsyncState;
Socket client = oldserver.EndAccept(iar);
Console.WriteLine(client.RemoteEndPoint.ToString() + " connected");
byte[] message = Encoding.ASCII.GetBytes("Welcome");
client.BeginSend(message, 0, message.Length, SocketFlags.None, new AsyncCallback(SendData), client);
}
void SendData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int sent = client.EndSend(iar);
client.BeginReceive(data, 0, size, SocketFlags.None, new AsyncCallback(ReceiveData), client);
}
void ReceiveData(IAsyncResult iar)
{
Socket client = (Socket)iar.AsyncState;
int recv = client.EndReceive(iar);
if (recv == 0)
{
client.Close();
server.BeginAccept(new AsyncCallback(AcceptCon), server);
return;
}
string receivedData = Encoding.ASCII.GetString(data, 0, recv);
byte[] message2 = Encoding.ASCII.GetBytes("reply");
client.BeginSend(message2, 0, message2.Length, SocketFlags.None, new AsyncCallback(SendData), client);
}
}