Home   Cover Cover Cover Cover
 

Time server (parallel requests)

Chap4_Ex16.cs
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Collections;

public class ClientHandler {
  private Socket cs;
  private Thread t;
  private bool busy = true;

  public ClientHandler(Socket s) {
    cs = s;
    t = new Thread(new ThreadStart(Process));
    t.Start();
  }

  public void Process() {
    byte[] b = Encoding.ASCII.GetBytes(DateTime.Now.ToString());
    cs.Send(b);
    cs.Shutdown(SocketShutdown.Both);
    cs.Close ();
    busy = false;
  }

  public bool Busy {
    get { return busy; }
  }
}

public class TimeServer {
  private Socket s;
  private ArrayList al;

  public TimeServer() {
    al = new ArrayList();
  }

  public bool StartUp(IPAddress ip, int port) {
    try {
      s = new Socket(  AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
      s.Bind(new IPEndPoint(ip, port));
      s.Listen(10); 
    } catch (Exception e) {
      Console.WriteLine(e.Message);
      return false;
    }
    for(;;) {
      al.Add(new ClientHandler(s.Accept())); // blocks until a client connects
      // clear list
      int i = 0;
      while(iif(!((ClientHandler)al[i]).Busy) al.RemoveAt(i);
        else i++;
      }
        
    }
  }
}

public class Chap4_Ex16_Test {
  public static void Main(string[] args) {
    TimeServer server = new TimeServer();
    if (! server.StartUp(IPAddress.Loopback, 50000))
      Console.WriteLine("Starting time server failed");
  }
}