473,803 Members | 2,949 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Async socks in a separate thread

Hi,

Could someone pls help me here:

If i use async sockets in the separate thread like this:

void ThreadFunction( )
{
.....
1. MySocket.BeginA ccept(AsyncCall Back(OnConnectR equest), MySocket);
2. ??????????
}

What do i do after line 1?
Do i put an endless loop in order to keep the thread alive?
And where do i put try{} catch{} to catch ThreadAbortExce ption thrown into the thread when i call Abort on the thread?

Thank you,
Andrey
Nov 16 '05 #1
8 3522
MuZZy,

-- FYI Managed Threading Best Practices does not recommend using Abort to
terminate a thread. Check item #1 in "General Recommendations " at this link:

http://msdn.microsoft.com/library/de...tpractices.asp

It's better to use your own event and/or boolean flag to signal that a
thread should stop processing.

-- I found the async socket documentation to be horrible... I burned up an
MSDN helpdesk call and got the following advice:

1) Do NOT try to use the manual wait handle returned with some async socket
APIs; it is not predictable. Declare and use your own events instead.

2) Your main listening loop should open the listener socket, issue
BeginAccept(), and then sleep until a connect attempt arrives or until the
program is stopped {this implies that you'll be waiting on 2 events}. When a
connection has been accepted by the callback handler loop around and issue
BeginAccept again.

Assuming that you have declared an event to signal program stop and an event
to signal an accepted connection, psuedo code for main listening loop looks
like this:

using (Socket listener = new Socket(...))
{
listener.Bind(. ..);
listener.Listen (...);

bool running = true;
while (running)
{
acceptEvent.Res et();
listener.BeginA ccept(new AsyncCallback(A cceptCallback), listener);
switch (WaitHandle.Wai tAny(acceptEven t, stopEvent))
{
case 0:
// acceptEvent - client connected, loop around again
break;
default:
// stopEvent or wait error - fall out of loop
running = false;
break;
}
}
}

3) When a client attempts to connect the accept callback handler should
issue EndAccept, signal the main thread that it has accepted a connection,
and then hand the accepted client off to another thread. The accept handler
MUST NOT process the client socket, it must EndAccept and return ASAP.

Assuming the "acceptEven t" from above, here is a working callback handler
that accepts a client connection, queues the client to the thread pool for
further processing, then signals the main loop that a client has been
accepted:

void AcceptCallback( IAsyncResult ar)
{
try
{
Socket socket = ((Socket)ar.Asy ncState).EndAcc ept(ar);
ThreadPool.Queu eUserWorkItem(n ew WaitCallback(So cketMain), socket);
}
catch (Exception ex)
{
trace.Exception (ex);
}
finally
{
acceptEvent.Set ();
}
}

4) The ThreadPool handler "SocketMain " receives a connected socket and it
can do whatever it wishes to do with the client:

void SocketMain(obje ct o)
{
using (Socket socket = (Socket)o)
{
... Do whatever ...
}
}

--Richard

"MuZZy" wrote:
Hi,

Could someone pls help me here:

If i use async sockets in the separate thread like this:

void ThreadFunction( )
{
.....
1. MySocket.BeginA ccept(AsyncCall Back(OnConnectR equest), MySocket);
2. ??????????
}

What do i do after line 1?
Do i put an endless loop in order to keep the thread alive?
And where do i put try{} catch{} to catch ThreadAbortExce ption thrown into the thread when i call Abort on the thread?

Thank you,
Andrey

Nov 16 '05 #2
Sample snippet:
AsyncCallback OnConnectReques t;

void OnConnectReques t(IAsyncResult ar)
{

// you have a connection, now start to receive---
try
{
Socket s = ar.AsyncState as Socket;
Socket s2 = s.EndAccept(ar) ;
// Keep the "Accept" process in motion
s.BeginAccept(a cceptCallback, s);
// Create a state object for client
StateObject state = new StateObject();
state.WorkerSoc ket = s2;
// Start an async receive
state.WorkerSoc ket.BeginReceiv e(state.Bytes, 0,
state.Bytes.Len gth, 0, receiveCallback , state);
}
catch(SocketExc eption e)
{
Debug.WriteLine (e.Message);
Console.WriteLi ne( "SocketExceptio n:"+ e.Message);
}
return; // Return the thread to the pool
}

Note that BeginAccept is called from within the callback method.

There are lots of different ways to do this, and it can be pretty confusing.
Some pretty good sample code to get you started at MSDN online.
Just look up "Asynchrono us sockets".
--Peter

"MuZZy" <le*******@yaho o.com> wrote in message
news:JP******** ************@rc n.net...
Hi,

Could someone pls help me here:

If i use async sockets in the separate thread like this:

void ThreadFunction( )
{
.....
1. MySocket.BeginA ccept(AsyncCall Back(OnConnectR equest), MySocket);
2. ??????????
}

What do i do after line 1?
Do i put an endless loop in order to keep the thread alive?
And where do i put try{} catch{} to catch ThreadAbortExce ption thrown into
the thread when i call Abort on the thread?

Thank you,
Andrey

Nov 16 '05 #3
Peter Bromberg [C# MVP] wrote:
Sample snippet:
AsyncCallback OnConnectReques t;

void OnConnectReques t(IAsyncResult ar)
{

// you have a connection, now start to receive---
try
{
Socket s = ar.AsyncState as Socket;
Socket s2 = s.EndAccept(ar) ;
// Keep the "Accept" process in motion
s.BeginAccept(a cceptCallback, s);
// Create a state object for client
StateObject state = new StateObject();
state.WorkerSoc ket = s2;
// Start an async receive
state.WorkerSoc ket.BeginReceiv e(state.Bytes, 0,
state.Bytes.Len gth, 0, receiveCallback , state);
}
catch(SocketExc eption e)
{
Debug.WriteLine (e.Message);
Console.WriteLi ne( "SocketExceptio n:"+ e.Message);
}
return; // Return the thread to the pool
}

Note that BeginAccept is called from within the callback method.

There are lots of different ways to do this, and it can be pretty confusing.
Some pretty good sample code to get you started at MSDN online.
Just look up "Asynchrono us sockets".
--Peter
Thank you for the reply!
But thing is that i already have what you mentioned above,
i just need to know how to keep the thread function from returning
after i've initiated BeginAccept(... ).

Thank you,
Andrey


"MuZZy" <le*******@yaho o.com> wrote in message
news:JP******** ************@rc n.net...
Hi,

Could someone pls help me here:

If i use async sockets in the separate thread like this:

void ThreadFunction( )
{
.....
1. MySocket.BeginA ccept(AsyncCall Back(OnConnectR equest), MySocket);
2. ??????????
}

What do i do after line 1?
Do i put an endless loop in order to keep the thread alive?
And where do i put try{} catch{} to catch ThreadAbortExce ption thrown into
the thread when i call Abort on the thread?

Thank you,
Andrey


Nov 16 '05 #4
Or spawn a listener thread and let that block.
Nov 16 '05 #5
Peter Wone wrote:
Or spawn a listener thread and let that block.


What do you mean here?
Nov 16 '05 #6
>> Or spawn a listener thread and let that block.

What do you mean here?


Never mind blocking. This is how you do it.

This code is excerpted from a custom control I wrote for an embedded
webserver. I use it to fulfil requests for addition resources like CSS or
images when I use an embedded webserver to render HTML. You can make it pick
a random port, and the widget exposes a LocalBaseUrl property that tells
your app the base URL for connecting to itself. That's what baseURL is
about.

Sockets aren't that hard but it takes a mind that's twisted in a special
way.

THIS CODE IS COPYRIGHT TO ME AND ANYONE PLANNING ON USING IT IN A
COMMERCIAL APPLICATION CAN JOLLY WELL PUBLICLY CREDIT ME.

The next Indian contractor to send a peremptory "UGENT: PLS HELP" message to
my private email address will receive pictures of dead cows in his work
inbox unless the request is accompanied by an offer to pay for my time and
trouble.
....
private TcpListener tcpListener;
private bool useRandomPort = true;
private int tcpListenerPort = 8080;
private bool shouldListen = false;
private Thread ListenerThread;
private string baseURL;

....
public void Start() {
if (useRandomPort)
tcpListenerPort = (new Random()).Next( 16384,65535);
baseURL = "http://localhost:" + tcpListenerPort + "/";
tcpListener = new TcpListener(IPA ddress.Loopback ,tcpListenerPor t);
if ((VirtualRoots. Count>0) && (null==filesys) )
filesys = new WebResourceProv iderFileSystem( );
shouldListen = true;
tcpListener.Sta rt();
ListenerThread = new Thread(new ThreadStart(Lis ten));
ListenerThread. Priority = ThreadPriority. BelowNormal;
ListenerThread. Name = string.Format(" {0} HTTP
Listener",this. GetType().ToStr ing());
ListenerThread. Start();
}
public void Stop() {
shouldListen = false;
}
....
private void Listen(){
while (shouldListen) {
if (tcpListener.Pe nding()){
Socket socket = tcpListener.Acc eptSocket();
socket.Blocking = false;
//Some applications disconnect immediately when just checking
//the continued presence of this app. These produce SelectError.
if (!socket.Poll(5 000,SelectMode. SelectError)) {
//spawn another thread to handle this request
HttpRequestHand ler handler = new
HttpRequestHand ler(this,socket );
Thread newThread = new Thread(new ThreadStart(han dler.Exec));
newThread.Name = string.Format(" {0} request
handler",this.G etType().ToStri ng());
newThread.Start ();
}
} else
Thread.Sleep(20 0);
}
}
Nov 16 '05 #7
> The next Indian contractor to send a peremptory "UGENT: PLS HELP" message
to my private email address will receive pictures of dead cows in his work

That comment was in poor taste. I hope you realize that.

--
Regards,
Alvin Bruney

[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ http://tinyurl.com/27cok
----------------------------------------------------------
"Peter Wone" <pe****@wamoz.c om> wrote in message
news:Ox******** ******@TK2MSFTN GP15.phx.gbl...
Or spawn a listener thread and let that block.


What do you mean here?


Never mind blocking. This is how you do it.

This code is excerpted from a custom control I wrote for an embedded
webserver. I use it to fulfil requests for addition resources like CSS or
images when I use an embedded webserver to render HTML. You can make it
pick a random port, and the widget exposes a LocalBaseUrl property that
tells your app the base URL for connecting to itself. That's what baseURL
is about.

Sockets aren't that hard but it takes a mind that's twisted in a special
way.

THIS CODE IS COPYRIGHT TO ME AND ANYONE PLANNING ON USING IT IN A
COMMERCIAL APPLICATION CAN JOLLY WELL PUBLICLY CREDIT ME.

The next Indian contractor to send a peremptory "UGENT: PLS HELP" message
to my private email address will receive pictures of dead cows in his work
inbox unless the request is accompanied by an offer to pay for my time and
trouble.
...
private TcpListener tcpListener;
private bool useRandomPort = true;
private int tcpListenerPort = 8080;
private bool shouldListen = false;
private Thread ListenerThread;
private string baseURL;

...
public void Start() {
if (useRandomPort)
tcpListenerPort = (new Random()).Next( 16384,65535);
baseURL = "http://localhost:" + tcpListenerPort + "/";
tcpListener = new TcpListener(IPA ddress.Loopback ,tcpListenerPor t);
if ((VirtualRoots. Count>0) && (null==filesys) )
filesys = new WebResourceProv iderFileSystem( );
shouldListen = true;
tcpListener.Sta rt();
ListenerThread = new Thread(new ThreadStart(Lis ten));
ListenerThread. Priority = ThreadPriority. BelowNormal;
ListenerThread. Name = string.Format(" {0} HTTP
Listener",this. GetType().ToStr ing());
ListenerThread. Start();
}
public void Stop() {
shouldListen = false;
}
...
private void Listen(){
while (shouldListen) {
if (tcpListener.Pe nding()){
Socket socket = tcpListener.Acc eptSocket();
socket.Blocking = false;
//Some applications disconnect immediately when just checking
//the continued presence of this app. These produce SelectError.
if (!socket.Poll(5 000,SelectMode. SelectError)) {
//spawn another thread to handle this request
HttpRequestHand ler handler = new
HttpRequestHand ler(this,socket );
Thread newThread = new Thread(new ThreadStart(han dler.Exec));
newThread.Name = string.Format(" {0} request
handler",this.G etType().ToStri ng());
newThread.Start ();
}
} else
Thread.Sleep(20 0);
}
}

Nov 16 '05 #8
So are the peremptory demands to do unpaid work that they get paid for.

"Alvin Bruney [MVP]" <vapor at steaming post office> wrote in message
news:Ot******** ******@TK2MSFTN GP15.phx.gbl...
The next Indian contractor to send a peremptory "UGENT: PLS HELP" message
to my private email address will receive pictures of dead cows in his
work

That comment was in poor taste. I hope you realize that.

--
Regards,
Alvin Bruney

[Shameless Author plug]
The Microsoft Office Web Components Black Book with .NET
Now Available @ http://tinyurl.com/27cok
----------------------------------------------------------
"Peter Wone" <pe****@wamoz.c om> wrote in message
news:Ox******** ******@TK2MSFTN GP15.phx.gbl...
Or spawn a listener thread and let that block.

What do you mean here?


Never mind blocking. This is how you do it.

This code is excerpted from a custom control I wrote for an embedded
webserver. I use it to fulfil requests for addition resources like CSS or
images when I use an embedded webserver to render HTML. You can make it
pick a random port, and the widget exposes a LocalBaseUrl property that
tells your app the base URL for connecting to itself. That's what baseURL
is about.

Sockets aren't that hard but it takes a mind that's twisted in a special
way.

THIS CODE IS COPYRIGHT TO ME AND ANYONE PLANNING ON USING IT IN A
COMMERCIAL APPLICATION CAN JOLLY WELL PUBLICLY CREDIT ME.

The next Indian contractor to send a peremptory "UGENT: PLS HELP" message
to my private email address will receive pictures of dead cows in his
work inbox unless the request is accompanied by an offer to pay for my
time and trouble.
...
private TcpListener tcpListener;
private bool useRandomPort = true;
private int tcpListenerPort = 8080;
private bool shouldListen = false;
private Thread ListenerThread;
private string baseURL;

...
public void Start() {
if (useRandomPort)
tcpListenerPort = (new Random()).Next( 16384,65535);
baseURL = "http://localhost:" + tcpListenerPort + "/";
tcpListener = new TcpListener(IPA ddress.Loopback ,tcpListenerPor t);
if ((VirtualRoots. Count>0) && (null==filesys) )
filesys = new WebResourceProv iderFileSystem( );
shouldListen = true;
tcpListener.Sta rt();
ListenerThread = new Thread(new ThreadStart(Lis ten));
ListenerThread. Priority = ThreadPriority. BelowNormal;
ListenerThread. Name = string.Format(" {0} HTTP
Listener",this. GetType().ToStr ing());
ListenerThread. Start();
}
public void Stop() {
shouldListen = false;
}
...
private void Listen(){
while (shouldListen) {
if (tcpListener.Pe nding()){
Socket socket = tcpListener.Acc eptSocket();
socket.Blocking = false;
//Some applications disconnect immediately when just checking
//the continued presence of this app. These produce SelectError.
if (!socket.Poll(5 000,SelectMode. SelectError)) {
//spawn another thread to handle this request
HttpRequestHand ler handler = new
HttpRequestHand ler(this,socket );
Thread newThread = new Thread(new ThreadStart(han dler.Exec));
newThread.Name = string.Format(" {0} request
handler",this.G etType().ToStri ng());
newThread.Start ();
}
} else
Thread.Sleep(20 0);
}
}


Nov 16 '05 #9

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

Similar topics

1
3404
by: Marwan | last post by:
Hello I am using asynchronous delegates to make a call to a COM ActiveX object, but even though the call occurs on a separate thread, my UI is still blocking. If i put the thread to sleep in my delegate call, the application is well behaved (no UI freeze), but the call to the com object causes the UI to lock up Do I have to manage calls to an ActiveX object differently than using the BeginInvoke and a callback A sample of the code I...
1
2429
by: Ben | last post by:
I've written a fair amount of sockets code using the Winsock2 API, but I am having some trouble converting to the .Net Sockets API, specifically asynchronous sockets. What I have is a form that is both a client and a server. When the form starts I create a listening socket and call Socket.BeginAccept(). When a client connects my accept function is called, and it is on a separate thread. After I accept the client connection I connect to...
5
11732
by: mscirri | last post by:
The code below is what I am using to asynchronously get data from a PocketPC device. The data comes in fine in blocks of 1024 bytes but even when I send no data from the PocketPC constant blocks of 1024 with all values set to Null arrive. Other than examine a block of 1024 to see if the entire block is null, is there any other way to determine if , say a chat message "Hi Charlie" has been received completely?
1
1594
by: milesm | last post by:
I've spent the last 3 hours reading various MSDN articles, other site articles and news group postings and was wondering what the best approach to my situation would be since I'm unable to come up with the best approach. What's Needed........ 1. Various background SQL inserts that don't interrupt the client request/response 2. Various background emails generated and sent that are separate from the client request/response 3. Every...
6
3827
by: Shak | last post by:
Hi all, Three questions really: 1) The async call to the networkstream's endread() (or even endxxx() in general) blocks. Async calls are made on the threadpool - aren't we advised not to cause these to block? 2) You can connect together a binaryreader to a networkstream:
7
2869
by: Shak | last post by:
Hi all, I'm trying to write a thread-safe async method to send a message of the form (type)(contents). My model is as follows: private void SendMessage(int type, string message) { //lets send the messagetype via async NetworkStream ns = client.GetStream(); //assume client globally accessible
12
3475
by: =?Utf-8?B?cGI=?= | last post by:
I am having trouble doing a redirect in an async asp.net implemention. Most of the time it works, but when it doesn't it just "hangs", the browser never gets any return page. If I run it under the debugger, it works fine, though every so often I get a HttpException. System.Web.HttpException was caught ErrorCode=-2147024809 Message="An error occurred while communicating with the remote host. The error code is 0x80070057."...
3
1509
by: =?Utf-8?B?TW9oYW4gQmFidSBE?= | last post by:
Hi, Here is my problem. I am calling a web service asynchronously as follows Registred the event handler as follows _Data.GetDataCompleted += new MyNameSpace.GetDataCompleted EventHandler(GetControlDataCompleted);
3
2689
by: Ryan Liu | last post by:
Will TcpClient.GetStream().Read()/ReadByte() block until at least one byte of data can be read? In a Client/Server application, what does it mean at the end of stream/no more data available? Client could send data once few seconds of minutes. Is there an "end" at all? In a C/S application, if server side call BeginginRead() again in EndRead() to create a endless loop to get message from client, is this a better approach than "one...
0
9703
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
9566
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
10555
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. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10317
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...
0
9127
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...
0
5503
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
4277
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
3802
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2974
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.