473,550 Members | 2,391 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

socket -client

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 ();
}
}

Dec 2 '05 #1
8 2727
define global list e.g. ArraList

ArraList client = new ArrayList(25);

and in method startlisten you initalize the list with instances of client
class.

client class must have property TcpClient. This property will be used
instead of contructor.
So the here is the control flow. You recevie connection check in the list
what class has TcpClient == null, pick it from the list, initialize
TcpClient and use....

All of these operations have to be synchronized as you'are working on
multiple threads.

--
Vadym Stetsyak aka Vadmyst
http://vadmyst.blogspot.com
"Ankit Aneja" <ef*****@newsgr oups.nospam> wrote in message
news:Oi******** *******@TK2MSFT NGP11.phx.gbl.. .
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 ();
}
}

Dec 2 '05 #2
Hi Ankit,

I think you're trying to implement a socket pool that has a limit of
clients. In this case, you can put a count when creating thread in the
while block. When the limit is reached, do not create any more threads.
Here is an article that might help you on this issue.

http://www.codeproject.com/internet/jbsocketserver1.asp

http://www.codeproject.com/internet/jbsocketserver2.asp

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Dec 2 '05 #3
Can you give me the example for
" and in method startlisten you initalize the list with instances of client
class.

client class must have property TcpClient. This property will be used
instead of contructor.
So the here is the control flow. You recevie connection check in the list
what class has TcpClient == null, pick it from the list, initialize
TcpClient and use....

All of these operations have to be synchronized as you'are working on
multiple threads.
"
"Vadym Stetsyak" <va*****@ukr.ne t> wrote in message
news:ek******** ******@tk2msftn gp13.phx.gbl...
define global list e.g. ArraList

ArraList client = new ArrayList(25);

and in method startlisten you initalize the list with instances of client
class.

client class must have property TcpClient. This property will be used
instead of contructor.
So the here is the control flow. You recevie connection check in the list
what class has TcpClient == null, pick it from the list, initialize
TcpClient and use....

All of these operations have to be synchronized as you'are working on
multiple threads.

--
Vadym Stetsyak aka Vadmyst
http://vadmyst.blogspot.com
"Ankit Aneja" <ef*****@newsgr oups.nospam> wrote in message
news:Oi******** *******@TK2MSFT NGP11.phx.gbl.. .
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 ();
}
}


Dec 5 '05 #4
Hi Ankit

I think Vadym means to initialize an instance for each item in the array.

public void startlisten()
{
//..............
for(int i=0;i<25;i++)
{
clients[i] = new client();
}
//..............
}

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Dec 6 '05 #5
i am using this code but it is giving following error
System.NullRefe renceException' occurred in
Additional information: Object reference not set to an instance of an
object.

it is breaking on line:if(cl[i].status==true)
code for listen class
public class listen

{

TcpListener server=null;

Thread tcpthread=null;

client[] cl=new client[5];
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.

// for(int i=0;i<5;i++)

// {

// cl[i].status=true;

// }

Boolean flag;

while(true)

{ flag=false;

// Perform a blocking call to accept requests.

// You could also user server.AcceptSo cket() here.

for(int i=0;i<5;i++)

{

if(cl[i].status==true)

{

cl[i]= new client(server.A cceptTcpClient( ));

tcpthread=new Thread(new ThreadStart(cl[i].getClient));

tcpthread.Start ();

flag=true;

break;

}

}

if(flag!=true)

{

//display error message

}

}

}

}

code for client class

public class client

{

TcpClient tcpClient;

public Boolean status;

// Buffer for reading data

Byte[] bytes = new Byte[256];

String data = null;

public client()

{ //

// TODO: Add constructor logic here

//

//status=true;

}

public client(TcpClien t Client)

{

tcpClient =Client;

//

// TODO: Add constructor logic here

//

status=false;

}

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)

{

MessageBox.Show (se.ToString()) ;

}

// Shutdown and end connection

tcpClient.Close ();

status=true;

}

}

"Kevin Yu [MSFT]" <v-****@online.mic rosoft.com> wrote in message
news:ir******** *****@TK2MSFTNG XA02.phx.gbl...
Hi Ankit

I think Vadym means to initialize an instance for each item in the array.

public void startlisten()
{
//..............
for(int i=0;i<25;i++)
{
clients[i] = new client();
}
//..............
}

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Dec 7 '05 #6
Hi,

The cl at this point is an array with 5 nulls. You have to new a client
object for its reference. Or, you can check to see if the cl[i] is a null
reference first.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Dec 7 '05 #7
thanks
"Kevin Yu [MSFT]" <v-****@online.mic rosoft.com> wrote in message
news:J9******** ******@TK2MSFTN GXA02.phx.gbl.. .
Hi,

The cl at this point is an array with 5 nulls. You have to new a client
object for its reference. Or, you can check to see if the cl[i] is a null
reference first.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Dec 7 '05 #8
You're welcome.

Kevin Yu
=======
"This posting is provided "AS IS" with no warranties, and confers no
rights."

Dec 8 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

8
9270
by: simon place | last post by:
Spent some very frustrating hours recoding to find a way of closing a server socket, i'd not thought it would be any problem, however, after complete failure and as a last resort, i looked at the python wrapper module for sockets, and found that the close command doesn't actually call the underlying close! this didn't seem right, so i added...
4
2938
by: Scott Robinson | last post by:
I have been having trouble with the garbage collector and sockets. Unfortunately, google keeps telling me that the problem is the garbage collector ignoring dead (closed?) sockets instead of removing live ones. My problem is x.sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM) do_stuff(x.sock)
4
18096
by: Chris Tanger | last post by:
Context: C# System.Net.Sockets Socket created with constructor prarmeters Internetwork, Stream and TCP everything else is left at the default parameters and options except linger may be changed as I find appropriate. I am using the socket asynchronously by calling the BeingSend and BeginReceive calls. I would like to be able to call...
2
4143
by: Nuno Magalhaes | last post by:
I've got a simple problem I guess. How do I know when a connection is terminated without losing any data? I do something like the code below, but sometimes between socket.Receive and socket.Send I get the last chunk of data and am not able to retrieve it anymore cause the socket will be dead. Loop: { socket.Receive <----------- data...
10
5580
by: groups.20.thebriguy | last post by:
socket objects have a little quirk. If you try to receive 0 bytes on a blocking socket, they block. That is, if I call recv(0), it blocks (until some data arrives). I think that's wrong, but I don't want to argue that. I would like to create a subclass of socket that fixes the problem. Ideally, something like: class...
8
5984
by: Mark Fink | last post by:
I try to port a server application to Jython. At the moment I use Jython21\Lib\socket.py Currently I do face problems with casting the string "localhost" to the desired value: D:\AUT_TEST\workspace\JyFIT>jython fit/JyFitServer2.py localhost 1234 23 localhost Traceback (innermost last): File "fit/JyFitServer2.py", line 146, in ?
11
7683
by: hazz | last post by:
smtpClient.Send(message) is causing me problems as per specifics in the trace below. Email is sent but not without this error typically upon sending the second email, but sometimes when running the app, even the first time. The application will be required to be sending out repeated emails, about one every second or two. Must this be...
10
7380
by: Hendrik van Rooyen | last post by:
While doing a netstring implementation I noticed that if you build a record up using socket's recv(1), then when you close the remote end down, the recv(1) hangs, despite having a short time out of 0.1 set. If however, you try to receive more than one char, (I tested with 3, did not try 2), then when you shut the remote end down you do not...
4
16062
by: O.B. | last post by:
I have a socket configured as TCP and running as a listener. When I close socket, it doesn't always free up the port immediately. Even when no connections have been made to it. So when I open the socket again, the bind fails because the port is still in use. When I execute the code in "debug" mode, the problem never occurs. When I...
3
2224
by: Giampaolo Rodola' | last post by:
Hi there, since the socket.socket.family attribute has been introduced only in Python 2.5 and I need to have my application to be backward compatible with Python 2.3 and 2.4 I'd like to know how could I determine the family of a socket.socket instance which may be AF_INET or AF_INET6. Is there some kind of getsockopt() directive I could use?...
0
7488
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7761
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7845
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6101
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5403
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
5129
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3532
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1094
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
801
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.