using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Sockets;
using System.Text;
class ClientHandler
{
private byte[] buffer = new byte[256];
private Socket socket;
private NetworkStream networkStream;
private AsyncCallback callbackRead;
private AsyncCallback callbackWrite;
public ClientHandler(Socket socketForClient)
{
socket = socketForClient;
networkStream = new NetworkStream(socketForClient);
callbackRead = new AsyncCallback(this.OnReadComplete);
callbackWrite = new AsyncCallback(this.OnWriteComplete);
}
public void StartRead()
{
networkStream.BeginRead(buffer, 0, buffer.Length,callbackRead, null);
}
private void OnReadComplete(IAsyncResult ar)
{
int bytesRead = networkStream.EndRead(ar);
if (bytesRead > 0)
{
string s = System.Text.Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.Write(s);
networkStream.BeginWrite(buffer, 0, bytesRead, callbackWrite, null);
}
else
{
networkStream.Close();
socket.Close();
networkStream = null;
socket = null;
}
}
private void OnWriteComplete(IAsyncResult ar)
{
networkStream.EndWrite(ar);
networkStream.BeginRead(buffer, 0, buffer.Length,callbackRead, null);
}
}
public class AsynchNetworkServer
{
public static void Main()
{
IPAddress localAddr = IPAddress.Parse("127.0.0.1");
TcpListener tcpListener = new TcpListener(localAddr, 65000);
tcpListener.Start();
for (; ; )
{
Socket socketForClient = tcpListener.AcceptSocket();
ClientHandler handler =new ClientHandler(socketForClient);
handler.StartRead();
}
}
}