472,780 Members | 1,717 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,780 software developers and data experts.

Asynchronous Sockets and Threading

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 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!


Example Code:

The windows service calls the StartListener and StopListener methods

public void StartListener()
Socket ConnectionListener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
ConnectionListener.Bind( new IPEndPoint( HostAddress, PortNumber ) );
ConnectionListener.Listen( 10 );
while (!ShuttingDown)
ConnectionListener.BeginAccept( new AsyncCallback( ConnectionRequest ), ConnectionListener );

/// <summary>
/// Stop listening for clients
/// </summary>
public void StopListener()
ShuttingDown = true;
Socket ConnectionListener = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp );
ConnectionListener.Connect( new IPEndPoint( HostAddress, PortNumber ) );
ConnectionListener.Shutdown( SocketShutdown.Both );
ConnectionListener = null;

private void ConnectionRequest( IAsyncResult ar )
Socket Listener = (Socket) ar.AsyncState;

Socket WorkingSocket = Listener.EndAccept( ar );
if ( ConnectedClients.Count < MaximumClients )
AcceptClient( WorkingSocket );
RefuseClient( WorkingSocket );

private void AcceptClient( Socket WorkingSocket )
Client Client = new Client();
Client.Connected += new Client.ConnectHandler( AddClient );
Client.Disconnected += new Client.DisconnectHandler( RemoveClient );
Client.WorkingSocket = WorkingSocket;

private void RefuseClient( Socket WorkingSocket )
WorkingSocket.Send( Encoding.ASCII.GetBytes("To many Clients") );
WorkingSocket.Shutdown( SocketShutdown.Both );
Jul 21 '05 #1
0 1243

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

Similar topics

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...
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...
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,...
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...
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...
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 thru Try If...
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. ...
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...
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...
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...
by: erikbower65 | last post by:
Using CodiumAI's pr-agent is simple and powerful. Follow these steps: 1. Install CodiumAI CLI: Ensure Node.js is installed, then run 'npm install -g codiumai' in the terminal. 2. Connect to...
by: linyimin | last post by:
Spring Startup Analyzer generates an interactive Spring application startup report that lets you understand what contributes to the application startup time and helps to optimize it. Support for...
by: kcodez | last post by:
As a H5 game development enthusiast, I recently wrote a very interesting little game - Toy Claw ((http://claw.kjeek.com/))。Here I will summarize and share the development experience here, and hope it...
by: Taofi | last post by:
I try to insert a new record but the error message says the number of query names and destination fields are not the same This are my field names ID, Budgeted, Actual, Status and Differences ...
by: DJRhino1175 | last post by:
When I run this code I get an error, its Run-time error# 424 Object required...This is my first attempt at doing something like this. I test the entire code and it worked until I added this - If...
by: Rina0 | last post by:
I am looking for a Python code to find the longest common subsequence of two strings. I found this blog post that describes the length of longest common subsequence problem and provides a solution in...
by: lllomh | last post by:
Define the method first this.state = { buttonBackgroundColor: 'green', isBlinking: false, // A new status is added to identify whether the button is blinking or not } autoStart=()=>{
by: Mushico | last post by:
How to calculate date of retirement from date of birth
by: DJRhino | last post by:
Was curious if anyone else was having this same issue or not.... I was just Up/Down graded to windows 11 and now my access combo boxes are not acting right. With win 10 I could start typing...

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.