473,915 Members | 3,885 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 2755
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
9293
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 it, and my code now works simply and as expected. def close(self):
4
2958
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
18155
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 shutdown and close asynchronously if possible.
2
4164
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 arrives
10
5632
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 new_socket(socket): def recv( self, bufsize, flags=0 ):
8
6019
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
7748
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 done asynchronously? Thank you. -Greg I get the generic error messages;
10
7422
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 get a time out, but an empty string - the normal end of file, I suppose. Has anybody else seen...
4
16210
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 execute the same code in release mode, the problem appears about 20% of the time. Here's the code:
3
2249
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? For now I've been able to determine the family by using: # self.socket = a connected...
0
10039
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9883
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10543
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 choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
8102
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 instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
7259
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 into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5944
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
6149
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4779
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
3370
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.