i am doing here some some socket-client work in C# windows service
it is working fine for multiple clients
now i want to limit these multiple clients to 25 for example
i want that when service starts objects for all these 25 clients
are created and when client connects it should be accepted and will not
allow more than 25 clients to connect
and when client diconnects that object can be allocated to another client
who requests
i am not able to make up logic how i will first create 25 objects and store
them in array
and how i will be checking wether object is free or not to be allocated to
another client
code:
protected override void OnStart(string[] args)
{
// TODO: Add code here to start your service.
listen obj;
Thread threadlisten=nu ll;
obj=new listen();
threadlisten =new Thread(new ThreadStart(obj .startlisten));
threadlisten.St art();
}
in listen class listen.cs
public class listen
{
TcpListener server=null;
Thread tcpthread=null;
client cl=null;
public listen()
{
//
// TODO: Add constructor logic here
//
}
public void startlisten()
{
Int32 port = 3310;
IPAddress localAddr = IPAddress.Parse ("192.168.0.5") ;
// TcpListener server = new TcpListener(por t);
server = new TcpListener(loc alAddr, port);
// Start listening for client requests.
server.Start();
// Enter the listening loop.
while(true)
{
// Perform a blocking call to accept requests.
// You could also user server.AcceptSo cket() here.
cl= new client(server.A cceptTcpClient( ));
tcpthread=new Thread(new ThreadStart(cl. getClient));
tcpthread.Start ();
}
}
public void stoplisten()
{
server.Stop();
}
}
in client class client.cs
public class client
{
TcpClient tcpClient;
// Buffer for reading data
Byte[] bytes = new Byte[256];
String data = null;
public client(TcpClien t Client)
{
//
// TODO: Add constructor logic here
tcpClient =Client;
}
public void getClient()
{
try
{
data = null;
// Get a stream object for reading and writing
NetworkStream stream = tcpClient.GetSt ream();
int i;
// Loop to receive all the data sent by the client.
while((i = stream.Read(byt es, 0, bytes.Length))! =0)
{
// Translate data bytes to a ASCII string.
data = System.Text.Enc oding.ASCII.Get String(bytes, 0, i);
// Process the data sent by the client.
string replyMsg = data;
clamdCommand x=new clamdCommand();
replyMsg=x.Comm and(replyMsg);
byte[] msg = System.Text.Enc oding.ASCII.Get Bytes(replyMsg) ;
// Send back a response.
stream.Write(ms g, 0, msg.Length);
//Console.WriteLi ne(String.Forma t("Sent: {0}", data));
}
}
catch(Exception se)
{
}
// Shutdown and end connection
tcpClient.Close ();
}
}