473,732 Members | 2,219 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Asynchronous Sockets and Threading

Dear all,

I have written a TCP server as a windows service that accepts connections using the System.Net.Sock ets.Socket class. I use the various asynchronous methods in the socket class. I'm having a problem at the moment when I shut the service down. When I stop the service I attempt to shutdown and close the socket. But when the service is started again and the Socket.Bind statement is encountered, an error occurs telling me that it is already in use? How can this be if I have shutdown and closed the socket?

Further more can anyone explain what happens when an Asynchronous method is called. Is a new thread allocated for the callback? If the method has been called before in the socket do you get the same thread? I have stepped through the code using the debugger and I don't understand where the threads have been created.

Any information on these things would be gratefully received!

Darren

Example Code:

The windows service calls the StartListener and StopListener methods

public void StartListener()
{
Socket ConnectionListe ner = new Socket( AddressFamily.I nterNetwork, SocketType.Stre am, ProtocolType.Tc p );
ConnectionListe ner.Bind( new IPEndPoint( HostAddress, PortNumber ) );
ConnectionListe ner.Listen( 10 );
while (!ShuttingDown)
{
Listen.Reset();
ConnectionListe ner.BeginAccept ( new AsyncCallback( ConnectionReque st ), ConnectionListe ner );
Listen.WaitOne( );
}
}

/// <summary>
/// Stop listening for clients
/// </summary>
public void StopListener()
{
ShuttingDown = true;
Socket ConnectionListe ner = new Socket( AddressFamily.I nterNetwork, SocketType.Stre am, ProtocolType.Tc p );
ConnectionListe ner.Connect( new IPEndPoint( HostAddress, PortNumber ) );
ConnectionListe ner.Shutdown( SocketShutdown. Both );
ConnectionListe ner.Close();
ConnectionListe ner = null;
}

private void ConnectionReque st( IAsyncResult ar )
{
Socket Listener = (Socket) ar.AsyncState;

Socket WorkingSocket = Listener.EndAcc ept( ar );
if ( ConnectedClient s.Count < MaximumClients )
AcceptClient( WorkingSocket );
else
RefuseClient( WorkingSocket );

Listen.Set();
}
private void AcceptClient( Socket WorkingSocket )
{
Client Client = new Client();
Client.Connecte d += new Client.ConnectH andler( AddClient );
Client.Disconne cted += new Client.Disconne ctHandler( RemoveClient );
Client.WorkingS ocket = WorkingSocket;
}

private void RefuseClient( Socket WorkingSocket )
{
WorkingSocket.S end( Encoding.ASCII. GetBytes("To many Clients") );
WorkingSocket.S hutdown( SocketShutdown. Both );
WorkingSocket.C lose();
}
Jul 21 '05 #1
0 1320

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

Similar topics

3
2821
by: Corne Oosthuizen | last post by:
I'm writing a Telnet Server application using Asynchronous sockets. I spawn a listener thread to handel incomming connections and create a separate client socket for each new connection. I then set the new client socket to BeginReceive(). My problem: When two client socket connections send data
1
1558
by: Darren | last post by:
Dear all, I have written a TCP server as a windows service that accepts connections using the System.Net.Sockets.Socket class. I use the various asynchronous methods in the socket class. I'm having a problem at the moment when I shut the service down. When I stop the service I attempt to shutdown and close the socket. But when the service is started again and the Socket.Bind statement is encountered, an error occurs telling me that...
48
5426
by: Steve - DND | last post by:
I'm trying to determine if I need to make my application multi-threaded, or if it can be done with asynchronous programming. I realize that asynch calls do create a new thread in the background, but when they come back, they return to the thread that launched them, is that correct? If I go multi-threaded, then I just need to spawn a new thread for each new connection, right? What I'm doing here is making a service that accepts...
9
8672
by: Michael Lindsey | last post by:
I need to write a server app to send images to client GUIs that are outside of the server's domain. The client will have the file system path to the image but can not access the file system. I am trying to decide if I should use remoting vs. writing a server that uses networkstreams. I have read that networkstreams\tcp programming should be faster than remoting and is a better choice for what I am doing but that it is difficult to code.
7
2385
by: Colin | last post by:
I'm writing a little console socket server but I'm having some difficulty. Can I ask your advice - where is the best place to get some help on that topic? It would be nice if some people who knew what they were doing could take a look at my code and tell me where and why I'm going wrong. Any suggestions of groups or forums?
2
2355
by: Stressed Out Developer | last post by:
We have an application that has a 200 count loop that does the following: ' Each time thru the loop we pass the next IP Address is a range (aka 192.168.4.50 thru 192.168.4.254) Try If mUIO_Threads(i) Is Nothing Then mUIO_Threads(i) = New System.Threading.Thread(AddressOf mUIO_DAQ(i).InitDAQ) mUIO_Threads(i).Name = mUIO_DAQ(i).UIO_IPAddr mUIO_Threads(i).IsBackground = False
4
3820
by: taskswap | last post by:
I have a legacy application written in C that I'm trying to convert to C#. It processes a very large amount of data from many clients (actually, upstream servers - this is a mux) simultaneously. I've read through what must be dozens of ways to do socket communication in C#, and it seems they all devolve into three basic options - Socket.Select, IOCP through a native interface, and Asynchronous callbacks. I'm fine using Asynchronous...
2
6877
by: Macca | last post by:
My app has an asynchronous socket server. It will have 20 clients connected to the server. Each client sends data every 500 millisecondsThe Connections once established will not be closed unless there is a problem with the connection. I need to know which client has sent the incoming data as each client has its own buffer on my "server" app. I am using the standard asynch socket code from MSDN to listen for connections and they...
0
1624
by: Raymondr | last post by:
Hi, First a brief description of out application: We have a webapplication which calls a couple of webservices during one request (postback). These calls to the webservices are made concurrent using asynchronous webservices calls. The number of webservices called concurrent is between 1 and 18. The webservice calls are made using SSL with a X509 clientcertificate. The application is underhigh load
2
3433
by: Nicolas Le Gland | last post by:
Hello everyone here. This is my first post in this newsgroup, I hope I won't be to much off-topic. Feel free to redirect me to any better group. I am getting strange timing issues when failing to asynchronously connect sockets on closed or filtered ports, but I'm quite unsure if this is a PHP issue or my misunderstanding, as it seems that socket streams only wrap around <sys/socket.h>.
0
8774
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
9307
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9235
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8186
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 launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6735
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
6031
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
4550
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...
1
3261
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
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.