Re: How to handle multiple incoming TCP connections in Windows Services
- From: "Ignacio Machin \( .NET/ C# MVP \)" <machin TA laceupsolutions.com>
- Date: Tue, 26 Dec 2006 10:16:50 -0500
Hi,
Its very easy, you have a thread just receiving connections in a loop and
inserting the connections in a queue and then spawning a new thread
while(true)
{
Socket s = listener1.AcceptSocket();
syncedQueue.Enqueue( s );
new Thread( new ThreadStart( workerMethod) ).Start();
}
workerMethod()
{
Socket s = syncedQueue.Dequeue();
}
You have to use a synced queue though:
syncedqueue = Queue.Synchonize( new Queue() );
Pd:
all the above code was written here without checking msdn so it may not
compile
--
Ignacio Machin
machin AT laceupsolutions com
<sracherla@xxxxxxxxx> wrote in message
news:1167080746.216521.151080@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I am trying to write a simple windows service that accepts an incoming
request; receives a string input and sends a string output. I need this
connection to stay alive until the client closes it.
Also, I need the service to accept multiple incoming requests.
Here is the code:
public void Listen()
{
#region Commented Code
try
{
int portNumber = 500;
log.WriteEntry(this.ServiceName + ": Listening on port " + portNumber
+ " ...");
//TcpListener listener = new TcpListener(localEndPoint);
IPAddress localAddress = IPAddress.Parse("127.0.0.1");
TcpListener listener = new TcpListener(localAddress, 500);
listener.Start();
do
{
if (!pause)
{
#region TcpClient Method
TcpClient tcpClient = new TcpClient();
tcpClient = listener.AcceptTcpClient();
if (tcpClient != null)
{
log.WriteEntry("Connected to someone.");
string message = Receive(tcpClient);
log.WriteEntry("Received following message on " +
DateTime.Now.ToString() + " :" + message);
message = "Booya";
Send(tcpClient, message);
log.WriteEntry("Sent following message on " +
DateTime.Now.ToString() + " :" + message);
}
}
} while (canStopListening);
listener.Stop();
}
catch
{
throw;
}
#endregion
}
The code I have above works for one incoming request only. And the
service does not respond to any other futher incoming requests.
Any help will be greatly appreciated.
.
- Follow-Ups:
- References:
- Prev by Date: Re: Using serviceConnectionPoints
- Next by Date: avoid easy decompiling
- Previous by thread: Re: How to handle multiple incoming TCP connections in Windows Services
- Next by thread: Re: How to handle multiple incoming TCP connections in Windows Services
- Index(es):
Relevant Pages
|