Select Tcp Server : TCP Server « Network « C# / C Sharp






Select Tcp Server

 
/*
C# Network Programming 
by Richard Blum

Publisher: Sybex 
ISBN: 0782141765
*/
using System;
using System.Collections;
using System.Net;
using System.Net.Sockets;
using System.Text;

public class SelectTcpSrvr
{
   public static void Main()
   {
      ArrayList sockList = new ArrayList(2);
      ArrayList copyList = new ArrayList(2);
      Socket main = new Socket(AddressFamily.InterNetwork,
                         SocketType.Stream, ProtocolType.Tcp);

      IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9050);
      byte[] data = new byte[1024];
      string stringData;
      int recv;


      main.Bind(iep);
      main.Listen(2);

      Console.WriteLine("Waiting for 2 clients...");
      Socket client1 = main.Accept();
      IPEndPoint iep1 = (IPEndPoint)client1.RemoteEndPoint;
      client1.Send(Encoding.ASCII.GetBytes("Welcome to the server"));
      Console.WriteLine("Connected to {0}", iep1.ToString());
      sockList.Add(client1);

      Console.WriteLine("Waiting for 1 more client...");
      Socket client2 = main.Accept();
      IPEndPoint iep2 = (IPEndPoint)client2.RemoteEndPoint;
      Console.WriteLine("Connected to {0}", iep2.ToString());    
      client2.Send(Encoding.ASCII.GetBytes("Welcome to the server"));
      sockList.Add(client2);
      main.Close();

      while(true)
      {
         copyList = new ArrayList(sockList);
         Console.WriteLine("Monitoring {0} sockets...", copyList.Count);
         Socket.Select(copyList, null, null, 10000000);

         foreach(Socket client in copyList)
         {
            
            data = new byte[1024];
            recv = client.Receive(data);
            stringData = Encoding.ASCII.GetString(data, 0, recv);
            Console.WriteLine("Received: {0}", stringData);
            if (recv == 0)
            {
               iep = (IPEndPoint)client.RemoteEndPoint;
               Console.WriteLine("Client {0} disconnected.", iep.ToString());
               client.Close();
               sockList.Remove(client);
               if (sockList.Count == 0)
               {
                  Console.WriteLine("Last client disconnected, bye");
                  return;
               }
            }
            else
               client.Send(data, recv, SocketFlags.None);
         }
      }
   }
}

           
         
  








Related examples in the same category

1.Bad Tcp ServerBad Tcp Server
2.Fixed Tcp Server
3.Stream Tcp Server
4.Simple Tcp Server
5.Var Tcp Server
6.Employee Server
7.Network Order Server
8.Tcp Listener Sample
9.Async Tcp ServerAsync Tcp Server
10.Tcp Poll Server
11.Threaded Tcp Server
12.Picky Tcp Listener
13.TcpListener Class
14.Accepts a pending connection request