I am having a problem with my Socket.Select statment. I
have included the code below for reference. I basically
accept new sockets from clients and add them to an
ArrayList. I execute a Select() to see which ones have
data to be read. What is happening if at some point, when
my arraylist is at a certain number, and all of these
sockets have something to be read, I get an Index out of
range option when the Select() method is called. Anyway to
fix this?
public static void Main()
{
ArrayList sockList = new ArrayList();
ArrayList copyList = new ArrayList();
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;
TcpListener l = new TcpListener
(IPAddress.Any, 9050);
//main.Bind(iep);
//main.Listen(1);
l.Start();
try
{
while (true)
{
//System.Threading.Thread.Sleep(1000);
//if (main.Poll
(1000000,SelectMode.SelectRead))
if (l.Pending())
{
Socket client1 =
l.AcceptSocket();
// client1.set
IPEndPoint iep1 =
(IPEndPoint)client1.RemoteEndPoint;
Console.WriteLine
("Connected to {0}", iep1.ToString());
sockList.Add
(client1);
}
if (sockList.Count > 0)
{
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;
}
}
}
}
}
}
catch (SocketException ex)
{}
finally
{
//main.Close();
l.Stop();
}
}