.NET Threads sockets and asynchronous things

Status
Not open for further replies.

Wraith

Ars Tribunus Militum
1,712
For a hobby project i've found i need to be able to do io using a handle provided by a native api which only supports overlappyed io. It should be possible to do and i took the opportunity to learn how to do Begin* and callbacks correctly. Or that's what i thought.

I've put together a little test project just to work out a framework for sending and receiving date using callbacks. I've got a listener thread, a sending thread and a receiver thread. I'm using BeginAction and IAsyncResult's throughout. I'm hitting some peculiar problems though and while i'm sure there's something i'm missing or don't understand i can't work out what it is. I'm hoping someone can point out my mistake or tell me where i need to be reading to find my error(s).

I've uploaded my test project, c# vs2k8 : https://www.box.com/s/ex3qrmxuwz2djzau4kcv

I think i've got an issue with timing. I found that the more console output i added the longer it took to reproduce the problem. To get around that i added an indirection for output so that console writes are off on their own thread, the caller formats the message (mainly to get the right threadid) then queues up the write and moves back to whatever work it should be doing.

When i run the project in a few seconds i'll hit the breakpoint setup which indicates that a socket.EndReceive call returned 0 which is supposed to indicate that the socket was closed. Except i didn't close it, and the sending socket isn't closed so when the sender thread picks it at random and tries to send it blocks. Why do i get a 0 return when there is data available? I'm stumped.

So, those of you who are bored or want some reason to avoid your family please have a look and let me know if you have any ideas or questions.
 

svdsinner

Ars Legatus Legionis
15,152
Subscriptor
Wraith":36teqnaj said:
. . . which indicates that a socket.EndReceive call returned 0 which is supposed to indicate that the socket was closed.
No, .EndRecieve shouldn't close the socket, it just returns the read bytes. .Close() closes the socket. Call it explicitly if you want the socket closed.

Unrelated: I see you're using box.com. I just got an account last night, in hopes of replacing Google Drive. I know the Dropbox windows client is nice, stable and low-impact, while the Google Drive client (both on Windows and Android) is a resource-hogging, dog-slow piece of crap. How have you liked box.com? Does it sync with reasonable speed and reasonably low impact on performance?
 

Wraith

Ars Tribunus Militum
1,712
If you read the docs for socket.EndReceive it says that it will return the number of bytes read or 0 if the socket has been shutdown, so i interpret 0 to mean that the socket has shutdown because i have no other way to find out if the socket has been closed. Is this wrong? and if so how do detect socket closure? Calling every method or property i've tried on a socket which is closed yields an exception which is a crappy way to work out if i can/should continue to use it.

I only use box as a web based host i can stick files on to access remotely, i don't use most of the features like sync. That said they've been going for years now and seem to be pretty reliable. I've never had issue with the few features i've used.
 
Wraith":24tifrcw said:
For a hobby project i've found i need to be able to do io using a handle provided by a native api which only supports overlappyed io. It should be possible to do and i took the opportunity to learn how to do Begin* and callbacks correctly. Or that's what i thought.
I took a look at the code but there are some major issues, mainly
1. it's not entirely clear what it's supposed to be doing,
2. it's almost certainly overcomplicated for what it's supposed to be doing,
3. it's a mess. (you've left a lot of unused/commented/etc stuff in there, and without knowing what the problem definition is, it's not really worth the time to try to sort out what matters and what doesn't)

I'd like to know more about the native api and the 'overlapped io' you mention. I'm not sure you're approaching this problem correctly (but then again, I can't tell what the problem is).
 

Wraith

Ars Tribunus Militum
1,712
It's a project to learn things, it's been growing so yes it is a little messy in places. The problem i'm trying to solve is how not to use 1 or more threads per listening connection. The answer is to use Begin/End async methods. I'm trying to learn how to do that correctly. Ignore any code in comments it was probably replaced or irrelevant, any english in comments may indicate me trying to tell you|us something; read and judge.

The native api is the terminal services api. It has peculiarities. A channel name must be ansi even in the unicode functions and the handle it returns cannot be used with standard read/write functions only WTSVirtualChannelRead/Write and is not threadsafe. You can get a threadsafe handle to use with standard io functions but it can _only_ do overlapped io, it is also an error to close that handle. It's an old and crufty api.

There are 3 main parts:

ConnectionAcceptor listens for incoming connections and when it finds on completes the connection and passes the new socket out to an event subscriber.

DataSender keeps an array of socket connections. It uses a thread running a loop to pick a random data size and send random bytes filling that data size to the receiving end of the socket. Every now and then it chooses to close a socket, if it finds a socket which is null it will open a new one. This is a very rough way to generate lots of data quickly and to simulate connections coming and going.

DataReceiver keeps a list of socket connections and associated context objects. It BeginReceive's on all of the open connections with a callback into the context object and then waits on a ManualRestEvent which is part of the context. When a receive completes it is called back on a worker thread, this EndReceive's to get the bytes in the receive buffer and then copies those into the conteext and the event in the context. The DataReceiver wakes and uses the context which signalled to work out what to do with the data that has been sent and then either closes the socket (in this case sometimes in error) or goes into another BeginReceive cycle.

DataShared contains some logging to keep console io off the other threads and a debugging list to track closing connections, ignore this class it's a utility nothing more.

It's a socket based client-server connection prototype. It creates up to 60 connections and quickly sends random data to the server end. The server end uses async methods to wait for that data so i don't have to have as many threads as connections, this is the overlapped io part.

The problem is that sometimes a receive event will call back to completion and indicate that there were no bytes received, which the docs say means that socket has shutdown. The socket was not shutdown by me and indicates no error conditio in either the sender or the receiver. So why do i get 0 return?
 

Wraith

Ars Tribunus Militum
1,712
I've been spending more time on this and i'm a little closer to knowing what's going wrong but still can't work what i've done incorrectly. With some help from Lyme on the ars irc #programming channel i've got a replication i can explain now. I've also uploaded the latest source used to generate the output discussed below to the link in the original post, which i'll put here again just in case anyone wants to help.

I've got the program logging. The format uses a log entry token which is just an int incremented on each call to the log function using Interlocked.Increment, this is a sanity check to ensure that the events were written in the order that the appear on the screen. Then there's the thread name/id an indication of the part of the process the entry comes from and then some info. so it's like this:
Code:
[    int++][name] area: info

Here's what a well behaved part of the log looks like (in my opinion anyway)

Code:
[        11][Send] Sending   :  to=127.0.0.1:51478, b= 8297
[        12][Read] BeginRead :  id=127.0.0.1:51477
[        13][Read] BeginRead :  id=127.0.0.1:51478
[        14][  18] EndRead   :from=127.0.0.1:51478, b= 2048, t=3
[        15][Read] Receiving :from=127.0.0.1:51478, b= 2048, t=3
[        16][Read] Received  :from=127.0.0.1:51478, b= 2048, t=3
[        17][Read] BeginRead :  id=127.0.0.1:51478
[        18][  18] EndRead   :from=127.0.0.1:51478, b= 2048, t=4
[        19][Read] Receiving :from=127.0.0.1:51478, b= 2048, t=4
[        20][Read] Received  :from=127.0.0.1:51478, b= 2048, t=4
[        21][Read] BeginRead :  id=127.0.0.1:51478
[        22][  18] EndRead   :from=127.0.0.1:51478, b= 2048, t=5
[        23][Read] Receiving :from=127.0.0.1:51478, b= 2048, t=5
[        24][Read] Received  :from=127.0.0.1:51478, b= 2048, t=5
[        25][Read] BeginRead :  id=127.0.0.1:51478
[        26][  18] EndRead   :from=127.0.0.1:51478, b= 2048, t=6
[        27][Read] Receiving :from=127.0.0.1:51478, b= 2048, t=6
[        28][Read] Received  :from=127.0.0.1:51478, b= 2048, t=6
[        29][Read] BeginRead :  id=127.0.0.1:51478
[        30][  18] EndRead   :from=127.0.0.1:51478, b=  105, t=7
[        31][Read] Receiving :from=127.0.0.1:51478, b=  105, t=7
[        32][Read] Received  :from=127.0.0.1:51478, b=  105, t=7
[        33][Read] BeginRead :  id=127.0.0.1:51478
[        34][Send] Sending   :  to=127.0.0.1:51477, b= 3419
  • at 11 the Send thread sends 8297 randomly generated bytes at the receiving socket on port 51478.
  • at 13 the Read thread calls to begin reading and wait for data, this could have occured anytime before 11, it just happened not to in this case
  • at 14 the 18 worker thread executes the callback passed to BeginRead because there is data present. It generates a receive token (again interlocked.increment to ensure uniqueness etc) which is the t= value. It copies data and Set()'s a waithandle to wake the Read thread
  • at 15 the Read thread notifies that it has woken to receive data for the socket and prints the token
  • at 16 the read thread notifies that reading has completed (meaning the received data is now safe in another location) and prints the token
  • at 17 BeginRead is called to start another read, at this point the receive token will be zeroed and the wait handle Reset() so it can be waited on again.
  • The receive cycle happens 3 more times, the last time with less than the 2K buffer full of data. It all succeeds in order though.

The way i understand this there should be exactly one call to EndReceive for each call to BeginReceive. Even though i'm using async methods by calling Begin/End stuff the way the code is structured it is not possible to have two outstanding Receive calls on a single socket. I force reads on a single socket to be serial even though multiple sockets can be active at one time.

The only way for receive to be called on a socket once data has been received is to pass through the loop in the DataReceiver which hands off the data to be used by a higher layer (yet to be written) and then clears the buffer, the token and the waithandle ready for re-use.

It should not be possible to see multiple overlapping invocations of the receive callback method should it? I thought not but that looks like what i'm getting. Consider this log of the issue i'm trying to trace. Same log format as before but i've added ( and ) to the EndRead to signify the start and end of that method call

Code:
[       612][Send] Sending   :  to=127.0.0.1:51597, b= 6937
[       613][  16] EndRead(  :from=127.0.0.1:51597
[       614][  16] EndRead)  :from=127.0.0.1:51597, b= 2048, t=74
[       615][  15] EndRead(  :from=127.0.0.1:51597
[       616][Read] Receiving :from=127.0.0.1:51597, b= 2048, t=75
[       617][Read] Received  :from=127.0.0.1:51597, b= 2048, t=75
[       618][  15] EndRead)  :from=127.0.0.1:51597, b= 2048, t=75
[       619][Read] BeginRead :  id=127.0.0.1:51597
[       620][Read] Receiving :from=127.0.0.1:51597, b=    0, t=0
[       621][  15] EndRead(  :from=127.0.0.1:51597
[       622][  15] EndRead)  :from=127.0.0.1:51597, b= 2048, t=76
[       623][Read] Read      :Closed Error! 127.0.0.1:51597, available=793
Consider lines 613 to 618, and see if you can tell me how they occured in the order that they did. They did have to happen in that order or Interlocked.Increment is lying, which seems very very unlikely.
  • at 613 the receive callback occurs on worker 16, it ends a read at 614 and generates receive token 74
  • at 615 the receive callback occurs, AGAIN!, this time on worker 15 and ends a receive generating a new token 75.
Line 615 should not have been possible before 617, it is just after line 617 that BeginReceive is called again. This looks like i've just been called back twice with data for the same socket following a single call to BeginReceive. That is wrong isn't it?

Now i can break the received data into a separate object to the context object and put it in a queue of some sort which might work around this. What i really want to know is why i'm having this problem. What have i misunderstood, what is wrong here? Help!
 
I did a simple rewrite of your program (because I think that took less time than trying to debug the flow in your existing program) and I've found that even though your sends are theoretically synchronous, you can't immediately send data again or the program will eventually hang (likely if it hits the same socket? I'm not sure, have to look into this more). If I put a sleep of at least 200 milliseconds between sends, things run smoothly.

In your program, if you put a sleep of at least 1 second (200 millis didn't work in your program, not sure why), it should start working as expected. So in your DataSender.cs file, before the "if (close)" line, stick in a Thread.Sleep(1000) and see if that works for you.

I need to figure out why immediately sending again ends up hanging the program... hmmm. Must be a receiver thing? I think?

Oh, I know how to test this...
 

Wraith

Ars Tribunus Militum
1,712
If i remove the Thread.Sleep() in the DataSender loop it will hang. That wasn't why it was there but it is an interesting result. It may be that because the sends can start before the receiving socket is able to accept data that the send simply waits indefinately. Adding a sleep probably gives it just enough time to get the receive processing done so the receiver is available before the next send. In my opinion this would be an error but we'll see.

Can you replicate the sort of behaviour i'm seeing? The events occuring in the order the sometimes seem to doesn't make sense.

i'd be interested to see your rewrite. I don't see what i've got as particularly complicated. The threads make it hard to reason about but it's only small number of classes and a limited number of important functions.
 
I think I figured out the hang issue. It's because the sockets default to an infinite timeout for sending. Once I set a send timeout on the sockets, I get a lot of timeout errors, but I can leave out the thread sleep.

Then I guess the question is why are these sends timing out. Not entirely sure there.

You have a lot of code to go through, that isn't all logically connected. It's not wrong, but it's not ideal. I think you're using Threads too much. Especially in the case of the listener and the logger. You don't need threads for those classes. At any rate, I felt the functionality you were aiming for was easier to implement fresh than to go through 1k+ lines of existing code... a luxury I think most of us don't normally get! ;)

I'll figure out a good place to get this online shortly!
 

Wraith

Ars Tribunus Militum
1,712
I don't need a thread for the logger but i found that the more logging i added the longer it took for the problem to occur, i thought that this might be because it was taking time to write to the screeen. I added the log thread and now it replicates pretty consistantly in a second or two. Need? no, but it helps iterate the code more easily.

The listener i'd say i do need. Something needs to wait for connections and that waiting is a blocking action. Now i could add that functionality into the DataReceiver class but that seemed to be using one class to do two different jobs so i split the functions out.

The other 3 threads are main which waits on user input the sender and receiver. The interactions aren't too bad or shouldn't be if it all worked. The sending and receiving sides will end up split into different programs once i've got the message layer and protocol layers setup and testing correctly.

It's not pretty but then it isn't finished and polished. When it is finished it still might not be pretty but has to work first. There are things in there i don't need, there's a couple of volatiles and a memorybarrier which are the result of hoping without logic that it was just doing something silly.
 
edit: I should note that you're right that the logging output will affect your timing, which is why you want the logging to happen separately from the display. However, that doesn't mean you need a separate thread for the logger itself. It just means you need a shared thread-safe data structure where you can push in/pull out messages as fast as possible.

In the listener, the waiting action isn't blocking.

This is my listener:
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;

namespace SampleSocketApp
{
    public class Listener
    {
        public EventHandler<NewConnectionArgs> ConnectionAccepted;
        
        public Listener(IPEndPoint endpoint)
        {
            Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            socket.Bind(endpoint);
            socket.Listen(200);
            socket.BeginAccept(AcceptCallback, socket);
        }

        private void AcceptCallback(IAsyncResult result)
        {
            Socket socket = (Socket)result.AsyncState;
            Socket newSocket = socket.EndAccept(result);
            if (ConnectionAccepted != null && newSocket != null)
            {
                ConnectionAccepted(this, new NewConnectionArgs(newSocket));
            }
            else
            {
                Logger.Log("AcceptCallback error: eventhandler == null is {0} and socket == null is {1}", ConnectionAccepted == null, newSocket == null);
            }
            // start listening for new connections again, listener handles new connections serially
            socket.BeginAccept(AcceptCallback, socket);
        }
    }

    public class NewConnectionArgs : EventArgs
    {
        public Socket Socket { get; set; }

        public NewConnectionArgs(Socket socket)
        {
            this.Socket = socket;
        }
    }
}
BeginAccept is asynchronous and returns immediately. So you don't need to have it in a separate thread.

I think when a thing isn't finished and polished, it should have less code, not more. The last thing you want to do is add more code to something that isn't working the way it should.

Anyhow, feel free to check out this version and let me know if it's missing some critical functionality that yours covers. I did the best I could to have this mimic the functionality in yours, but I'm not necessarily sure I've covered everything. Especially the DataReceiverContext, I wasn't really sure if that was doing anything special or not.
https://www.box.com/s/u4p7u2144tyc9vymrqmx (just realized this solution was made with visual studio 2010, let me know if this works for you!)

additional bottom edit: I also have three main threads, the gui/winform thread, then two background worker threads for send/receive. I think really, the best would be to set up your listener/receiver in a dll that can be run as a standalone exe, or called as part of a library. That way you could demo it within another console app or winform app, but also have the ability to invoke it separately (as its own process), which is how I'd assume most projects would run.

I'll take a look at the updated project you put up and see if I can figure out that ordering issue, which I believe might have to do with the way you're dealing with socket closing...
 

Wraith

Ars Tribunus Militum
1,712
I think you may have missed part of my reason for doing this. A single case works fine as far as i know and if i drop back the number of senders to 1 or two i experience no problems. When i ramp it up to 60 i hit issues quickly.

Waiting to receive data is a blocking operation. Something somewhere has to do that waiting. At the moment that's commonly a thread either from the threadpool or a manually created thread. All the thread is going to do most of the time is wait. This is fine but how about when you're trying to handle 100 connections, 1000, how big can it get? I can't find an explicit reference unfortunately but threading does not scale well like this, you quickly end up spending lot of your time handling context switching and trying to bolt on synchronisation to let large numbers or client objects interact with your core objects. There is also the cost of per-thread resources and the cost of threads in clr and native object terms to consider.

What i'm trying to do it get this project to do the waiting using async operations and then provide a sychronised core api to let these operations happen as fast as i can without corrupting data. If it can't run as fast as it needs to then the failure mode needs to be well defined, detectable and understood.

I can only listen to ~62 receiving sockets on on DataReveiver instance at a time due to the limit of handles for the WaitAny call but even this cuts down dramatically on overhead. What it does do is move the complexity from computer memory into the programmer, the code has to be right because order of operations is now far more important than when you expect to have single relatively isolated thread use it.

I'm hitting this problem and i'm not sure why. It looks like it's a timing problem and if it is i really need to understand it and either how to avoid it or how not to cause it in the first place. If it isn't a timing problem then something beyond my understanding is happening and i need to know what.

I don't think it should be possible for multiple threads to be woken to service the same callback, i also don't think it should be possible for the callback to be called multiple times for a single begin-end cycle because there is no way for the system to know how long it will take me to handle the event that has occured, it has to wait for me to call begin again or the callback itself is unreliable because data can be overwritten at any time during execution.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
Line 615 should not have been possible before 617, it is just after line 617 that BeginReceive is called again. This looks like i've just been called back twice with data for the same socket following a single call to BeginReceive. That is wrong isn't it?
I think (based on intuition, not actually looking at the code, and a mere three hours of sleep) that your problem is that two threads are attached to the same socket and you're expecting the scheduler to read your mind. Both threads receive a callback simultaneously so that after thread 16 is randomly chosen to receive it, thread 15 gets cpu time next. THEN the Read thread. 15's already on the scheduler and Read doesn't bump it like you want it to. You're then trying to read for thread 16, then read for 15 AFTER you've sucked down 6k of the data. The next read expects that 2048 bytes still remain, except you only have 793. So it is a timing problem, except it's not - it's caused by multiple threads attaching to the same socket, the timing is a symptom.
 
Wraith":1cv62vxo said:
I think you may have missed part of my reason for doing this. A single case works fine as far as i know and if i drop back the number of senders to 1 or two i experience no problems. When i ramp it up to 60 i hit issues quickly.
Where in the code are you changing the number of senders? I'm looking at your latest project, you have 1 data sender with 1 thread that has an array of 3 data sockets. What exactly are you referring to when you say "sender"?

The code you posted does all the sending synchronously. You're calling Send, which is a synchronous method. The number of senders only changes the number of receivers on the other end, but not the number of threads that are active simultaneously. You're never sending data to more than one socket at a time.

Wraith":1cv62vxo said:
Waiting to receive data is a blocking operation. Something somewhere has to do that waiting. At the moment that's commonly a thread either from the threadpool or a manually created thread. All the thread is going to do most of the time is wait. This is fine but how about when you're trying to handle 100 connections, 1000, how big can it get? I can't find an explicit reference unfortunately but threading does not scale well like this, you quickly end up spending lot of your time handling context switching and trying to bolt on synchronisation to let large numbers or client objects interact with your core objects. There is also the cost of per-thread resources and the cost of threads in clr and native object terms to consider.

What i'm trying to do it get this project to do the waiting using async operations and then provide a sychronised core api to let these operations happen as fast as i can without corrupting data. If it can't run as fast as it needs to then the failure mode needs to be well defined, detectable and understood.

I can only listen to ~62 receiving sockets on on DataReveiver instance at a time due to the limit of handles for the WaitAny call but even this cuts down dramatically on overhead. What it does do is move the complexity from computer memory into the programmer, the code has to be right because order of operations is now far more important than when you expect to have single relatively isolated thread use it.

I'm hitting this problem and i'm not sure why. It looks like it's a timing problem and if it is i really need to understand it and either how to avoid it or how not to cause it in the first place. If it isn't a timing problem then something beyond my understanding is happening and i need to know what.

I don't think it should be possible for multiple threads to be woken to service the same callback, i also don't think it should be possible for the callback to be called multiple times for a single begin-end cycle because there is no way for the system to know how long it will take me to handle the event that has occured, it has to wait for me to call begin again or the callback itself is unreliable because data can be overwritten at any time during execution.
I don't understand what you're saying. The BeginReceive callback is asynchronous. Why are you doing WaitAny at all? Have you looked at the code I posted? If you change the max connection variable to 100, it still works fine. I'm positive the issue you're having is because you're adding extra multithreading concepts where you don't need them. Which is why things are happening in an order that you don't expect. You're hitting this problem because you don't understand the code you've written.

Any time I see code like this:
Code:
								DataShared.LogFlush();
								DataShared.LogFlush(); // no really, flush it
								DataShared.LogFlush(); // seriously
I assume the programmer doesn't know what his program is doing.

edit: Further research into callbacks reveals that I also don't know what my program is doing! :eek: Well, that's why this was interesting to me, I used to deal with threading issues in C# extensively but that was a few years ago. Apparently I'm out of the loop. I thought callbacks were handled the same as events, in which they happen on the same thread they were invoked on. I guess it's just any threadpool thread that's available, though. Since my program's collections are synchronous, that shouldn't affect the functionality, but it might explain the socket timeouts I'm seeing. Hmm. I still think you have too much threading infrastructure for what you want your program to do, but that's just intuition now... :p

http://stackoverflow.com/questions/5531 ... lbacks-run
 

Wraith

Ars Tribunus Militum
1,712
I fixed it a few of hours ago. The process of writing up the explanation that i didn't post this morning made me realise that i was on the right track and that the only likely explanation was that multiple wait callbacks were occuring at the same time. Given that premise i was able to identify how multiple receives were being called on the same target and eliminate the issue.

Now i'm looking into the other little issue you noticed where if there is no sleep in the sending thread it appears to hang. The good news is it doesn't hang anymore, the bad news is it hits a guard condition and throws but that's getting me somewhere.

I assume the programmer doesn't know what his program is doing.
Yes, i can see how you'd think that, but it isn't the case.

The program is moving so fast that multiple items can be written to the log queue in the time it takes to break into the debugger, the messages in the buffer are helpful to determine what happened. Those lines were an ineffective attempt to get it to flush them. It turns out the only real way to do that is to wait until it hits the breakpoint and then manually run the flush. Try it, you'll see.
 
Wraith":1n6ruplp said:
I fixed it a few of hours ago. The process of writing up the explanation that i didn't post this morning made me realise that i was on the right track and that the only likely explanation was that multiple wait callbacks were occuring at the same time. Given that premise i was able to identify how multiple receives were being called on the same target and eliminate the issue.

Now i'm looking into the other little issue you noticed where if there is no sleep in the sending thread it appears to hang. The good news is it doesn't hang anymore, the bad news is it hits a guard condition and throws but that's getting me somewhere.

I assume the programmer doesn't know what his program is doing.
Yes, i can see how you'd think that, but it isn't the case.

The program is moving so fast that multiple items can be written to the log queue in the time it takes to break into the debugger, the messages in the buffer are helpful to determine what happened. Those lines were an ineffective attempt to get it to flush them. It turns out the only real way to do that is to wait until it hits the breakpoint and then manually run the flush. Try it, you'll see.
Well, glad you're figuring out the issue! Was it in the receiver context or the receiver itself?

I think the multiple flush thing is a difference in the way we debug things. It sounds like you added those specifically to be able to flush based on breakpoints then? I don't tend to use breakpoints, especially in multithreaded applications.

I'll try and get my side a bit more debugged. Looks like the listener also did need at least one mutex to handle the 'fast-as-possible' case (sender would try to open a new connection before the begin accept was restarted).
 

Wraith

Ars Tribunus Militum
1,712
The problem was caused by the init case in the DataReceiver. It wasn't checking to see if a receive was pending for the socket it just blindly started one. That meant that when a socket was added causing the waithandle array to be re-initialised a new BeginReceive was called on an alrady receiving socket meaning there were now two callbacks.

This was fine until a callback was made for that socket and there was more than a single receive buffer of outstanding data available. The first callback completed the io with it's call to EndReceive which caused the second callback to be signalled, another available worker to be assigned to handle it and scheduled. Essentially it was what it seemed, two temporally overlapping events attempting to use the same DataReceiveContext object to receive two pieces of data at the same time and falling over doing so because that object was designed to be used in a serial manner.

Look up IO completion ports in the native windows api. They're what these async methods use to do io under the covers. It's not the threading you're used to with .net, it's doing the waits in the os.

I've got it using a full single cpu running as fast as it can and it seems to be working. I need to work out this sender issue and see if there's a way to avoid it then i've got to write a protocol, that'll be fun...
 
Wraith":3s6l25ig said:
The problem was caused by the init case in the DataReceiver. It wasn't checking to see if a receive was pending for the socket it just blindly started one. That meant that when a socket was added causing the waithandle array to be re-initialised a new BeginReceive was called on an alrady receiving socket meaning there were now two callbacks.
Oh, ok! Yeah, that makes sense. I have a dictionary of sockets and their receive state, so I don't believe I saw that issue.

Wraith":3s6l25ig said:
Look up IO completion ports in the native windows api. They're what these async methods use to do io under the covers. It's not the threading you're used to with .net, it's doing the waits in the os.
I don't understand what you're saying here... the code is still .net, no? What do you mean when you say "it's not the threading you're used to"? Are you saying async sockets behave differently than other async methods within the .net framework then?
 
Not that I think anyone cares at this point, but I think I have a decent sample of the functionality in a relatively compact form now. If anyone wants to look at this and point out any glaring issues, feel free to let me know!

I've noticed that now that I don't output any log info during execution, I don't have socket timeout issues, which makes me think it was logging output that caused the issue in the first place. I suppose that's easy to test, I'll rework the code and see if I can confirm my suspicions.
Code:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace SimpleSocketServer
{
    class Program
    {
        static void Main(string[] args)
        {
            IPEndPoint serverAddress = new IPEndPoint(new IPAddress(new byte[] { 127, 0, 0, 1 }), 8000);
            Server server = new Server(serverAddress);
            RandomClientGenerator.Generate(serverAddress, 5, 15);

            while (!RandomClientGenerator.Done) { Thread.Sleep(1000); Console.WriteLine(DateTime.Now.ToString("HH:mm:ss")); }

            server.Shutdown();

            if (RandomClientGenerator.Error)
                Console.WriteLine("ERROR");

            Console.WriteLine("End.");
            Console.ReadLine();
        }
    }

    public class Server
    {
        ConcurrentDictionary<string, Socket> _openSockets;
        private bool _isRunning = false;

        // start a server at the given endpoint
        public Server(IPEndPoint endpoint)
        {
            _openSockets = new ConcurrentDictionary<string, Socket>();
            _isRunning = true;
            Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            listener.Bind(endpoint);
            listener.Listen(200);
            listener.BeginAccept(AcceptCallback, listener);
        }

        private void AcceptCallback(IAsyncResult result)
        {
            if (!_isRunning) return;
            Socket listener = (Socket)result.AsyncState;
            Socket newSocket = listener.EndAccept(result);
            listener.BeginAccept(AcceptCallback, listener);
            if (!_openSockets.ContainsKey(newSocket.RemoteEndPoint.ToString()))
                _openSockets.AddOrUpdate(newSocket.RemoteEndPoint.ToString(), newSocket, (key, val) => newSocket);
            else
                throw new Exception("Socket open error!");
            ReceiverData r = new ReceiverData(newSocket);
            newSocket.BeginReceive(r.Buffer, 0, r.Buffer.Length, SocketFlags.None, ReceiveCallback, r);
        }

        private void ReceiveCallback(IAsyncResult result)
        {
            if (!_isRunning) return;
            ReceiverData r = (ReceiverData)result.AsyncState;
            int count = r.Socket.EndReceive(result);
            if (count == 0)
            {
                Socket tmp = null;
                string addr = r.Socket.RemoteEndPoint.ToString();
                r.Socket.Close();
                if (!_openSockets.TryRemove(addr, out tmp))
                    throw new Exception("Could not remove closed socket!");
            }
            else
            {
                r.Socket.BeginReceive(r.Buffer, 0, r.Buffer.Length, SocketFlags.None, ReceiveCallback, r);
            }
        }

        public void Shutdown()
        {
            _isRunning = false;
            foreach (Socket s in _openSockets.Values)
            {
                s.Shutdown(SocketShutdown.Both);
                s.Close();
            }
        }

        public class ReceiverData
        {
            public byte[] Buffer = new byte[16 * 1024];
            public Socket Socket { get; private set; }

            public ReceiverData(Socket socket)
            {
                this.Socket = socket;
            }
        }
    }

    public class Client
    {
        public Socket Socket { get; private set; }

        public Client(IPEndPoint server)
        {
            Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP);
            Socket.Connect(server);
            Socket.SendTimeout = 500;
        }

        public void SendData(byte[] bytes)
        {
            SocketError code = SocketError.SocketError;
            int result = Socket.Send(bytes, 0, bytes.Length, SocketFlags.None, out code);
            if (SocketError.Success != code) throw new Exception("Error sending data: " + code.ToString());
        }
    }

    public class RandomClientGenerator
    {
        private static Client[] _clients;
        private static Random _random;
        private static BackgroundWorker _bw;

        public static bool Done { get; private set; }
        public static bool Error { get; private set; }

        public static void Generate(IPEndPoint serverAddress, int numClients, int secondsToRun)
        {
            _random = new Random();
            _clients = new Client[numClients];
            _bw = new BackgroundWorker();
            _bw.DoWork += delegate { SendData(DateTime.Now.AddSeconds(secondsToRun), numClients, serverAddress); };
            _bw.RunWorkerAsync();
        }

        private static void SendData(DateTime endTime, int numClients, IPEndPoint serverAddress)
        {
            int idx = -1;
            while (DateTime.Now < endTime)
            {
                idx = _random.Next(0, numClients);
                if (_clients[idx] == null)
                {
                    _clients[idx] = new Client(serverAddress);
                }
                else if (_clients[idx].Socket.Connected)
                {
                    if ((_random.Next() % 17) == 0)
                    {
                        _clients[idx].Socket.Close();
                        _clients[idx] = null;
                    }
                    else
                    {
                        try
                        {
                            _clients[idx].SendData(RandomBytes());
                        }
                        catch (Exception)
                        {
                            Error = true;
                            break;
                        }
                    }
                }
            }
            Done = true;
        }

        private static byte[] RandomBytes()
        {
            int count = _random.Next(1, 16 * 1024);
            byte[] randomBytes = new byte[count];
            _random.NextBytes(randomBytes);
            return randomBytes;
        }    
    }
}
(Also, apologies if I'm hijacking your thread, Wraith! Clearly I don't have anything better to do with my holidays... :D )

edit: was doing some research on closing sockets properly, found this codeproject article that looks like it has a fairly extensive implementation of async socket operations, might be worth a look?
http://www.codeproject.com/Articles/831 ... Socket-Cod
 

Wraith

Ars Tribunus Militum
1,712
Hijack away, i think we're the only ones paying attention.

Ok, looks workable. One little thing. In your callbacks you check _isRunning and return immediately, you should always EndReceive or EndAccept even if you don't want to use the result you should let the system know that the queued item has been dealt with so it can release the queue. Note that EndReceive etc can throw exceptions if a timeout has occured, i'm not using timeouts but i could so i protected the call just in case.

The other main differences are that:

  • I choose to do manual locking. This is partly because i've been doing this since .net 1.0 and old habits die hard. I also find it helpful to delineate exactly what parts of the code are threadsafe because i should behave as if every other piece is not.
  • I'm causing receive events to be pushed back to my Read thread as soon as the received data has been copied into a buffer. Presumably if you were going send the data up to another layer you would keep running on the worker thread allowing the caller to deal with locking further up, i've chosen to resolve it at the lower level.

If you open a socket and call Send the method will block. The easy way to to introduce asynchronus operations with this is to cause this block to be on another thread that you don't care about particularly and let it just wait it out. You'd do that using ThreadPool.QueueUserWorkItem (also used by BackgroundWorker) or new Thread() and then set it up to call Send. When that thread unblocks if it ever does you do some work and then perhaps marshall an event back to the ui. It's still a blocking call it just blocks somewhere else. If you've got 1000 of these going on you've got 1000 things blocking and probably 1000 threads. Less than ideal because each of those has to be allocated managed and schduled.

When you use completion ports you don't block. The kernel scheduler does the waiting for you using it's internal knowledge of the entire system and it can be a lot smarter and faster about it than user mode can. You give it a file (in this case socket) handle and ask to be called back when an io operation completes. It'll setup a wait and when the io completes it finds a thread in your process which can be used to deal with the callback and calls back on it. This is the suggested method for handling large number of connections according to what i've read.

There's an interesting chunk about it in the Sysinternals Inside Windows book and there are programming docs about it for unmanaged code. Async* operations in .net wrap this os infrastructure and add bits and pieces to keep managed context and runtime constraints satisfied. I'm sure there are bits and pieces about it on the internet but i often find multiple sources confuse things by focussing poorly and inbuing their articles with their own misunderstandings.
 
Wraith":2ptb1bum said:
Ok, looks workable. One little thing. In your callbacks you check _isRunning and return immediately, you should always EndReceive or EndAccept even if you don't want to use the result you should let the system know that the queued item has been dealt with so it can release the queue. Note that EndReceive etc can throw exceptions if a timeout has occured, i'm not using timeouts but i could so i protected the call just in case.
That's actually why I was looking up how to close sockets properly. However, it appears that to clean up async sockets correctly, you pretty much have to complete a protocol, because there's no built-in method to inform the other side that you're closing before you close. For the sake of demonstration, I don't think it matters much. I was mostly ending up with object disposed exceptions, and I didn't feel like adding extra lines to handle the exceptions that I was going to ignore anyhow.
I choose to do manual locking. This is partly because i've been doing this since .net 1.0 and old habits die hard. I also find it helpful to delineate exactly what parts of the code are threadsafe because i should behave as if every other piece is not.
I'm not going to lie, I did my C# threading code years ago and I'm not exactly up to date with the latest C# stuff, but your code still looks dated to me! Must be the 1.0ness. I'm not sure I agree with the extra manual locking, and I would likely disagree with having that code introduced in the workplace without good justification, since it's an additional layer of complexity that (presumably) isn't strictly required. In terms of a personal project, though, that doesn't matter. :)
I'm causing receive events to be pushed back to my Read thread as soon as the received data has been copied into a buffer. Presumably if you were going send the data up to another layer you would keep running on the worker thread allowing the caller to deal with locking further up, i've chosen to resolve it at the lower level.
Well, in your code now, you aren't actually doing anything with the event handler from the main thread, right? I assume you mean the DataReceived event in your DataReceiver? It's different than my implementation, but as far as what the program was actually doing, I don't think it changes anything. There are definitely a lot of things that could be adjusted to make this more workable for a real solution, but in this case, I just wanted a short implementation that would reasonably fit in a post and mimic the core functionality of your example. Easiest way to get people to look at code is to have it all there in front of them! Heh.
If you open a socket and call Send the method will block. The easy way to to introduce asynchronus operations with this is to cause this block to be on another thread that you don't care about particularly and let it just wait it out. You'd do that using ThreadPool.QueueUserWorkItem (also used by BackgroundWorker) or new Thread() and then set it up to call Send. When that thread unblocks if it ever does you do some work and then perhaps marshall an event back to the ui. It's still a blocking call it just blocks somewhere else. If you've got 1000 of these going on you've got 1000 things blocking and probably 1000 threads. Less than ideal because each of those has to be allocated managed and schduled.

When you use completion ports you don't block. The kernel scheduler does the waiting for you using it's internal knowledge of the entire system and it can be a lot smarter and faster about it than user mode can. You give it a file (in this case socket) handle and ask to be called back when an io operation completes. It'll setup a wait and when the io completes it finds a thread in your process which can be used to deal with the callback and calls back on it. This is the suggested method for handling large number of connections according to what i've read.

There's an interesting chunk about it in the Sysinternals Inside Windows book and there are programming docs about it for unmanaged code. Async* operations in .net wrap this os infrastructure and add bits and pieces to keep managed context and runtime constraints satisfied. I'm sure there are bits and pieces about it on the internet but i often find multiple sources confuse things by focussing poorly and inbuing their articles with their own misunderstandings.
I got a bit confused here because you started talking about the Send method. For some reason I associated Send with Clients, but that's not necessarily true. I guess I'm not sure why you mention that this isn't "the threading you're used to"... this is how the async operations were designed. I'm not used to them happening any other way! The main convenience of using the built-in constructs is that it allows the programmer to avoid worrying about thread priority, number of threads, or thread contention. As long as they understand how to initiate the call and how to handle the callback, they don't have to worry about the rest (at least, until it doesn't work the way it's supposed to, but that never happens, right?). I think maybe you're used to things working differently from before I started working with C#... ;)

Anyhow, this was a fun little project to do some C# coding again! I'm not sure I helped you at all, but I got a lot out of it. :D
 

tinyMan

Ars Tribunus Angusticlavius
6,149
Subscriptor++
Guess I missed where this was related to RDP. Mostly I was looking over the code posted by gaijin which looks to be a 100% standard sockets based tcp network application.

Perhaps it doesn't apply to the OPs code, but gaijin's code could be replaced with a handful of lines of code using zeroMq and the clrzmq (in Nuget) bindings for CLR.

I'd have to be in some pretty odd scenario (like somehow having to use RDP as my message transport) to be caught dealing with sockets directly these days. Too many pitfalls and boilerplate required.
 

Wraith

Ars Tribunus Militum
1,712
Once i get back to the RDP parts it'll be looking more like file access i think, i'll still need a protocol to let me work out where content is in the incoming stream. I chose to mess with sockets because i wanted to know how to do the async stuff and they're an easy way to get relatively disconnected client-server sides of soemthing that can be done in an async way. I should add BeginSend really.

Yes, gaijin's code does looks pretty simple but as i said in an earlier post it doesn't have all the functionality i wanted. Principally it handles all data on the callback thread which is undesirable to me. I receive and marshall back to a central handling thread to let data be moved up into the protocol layer which will sit above. This is what i blathered about on irc because the sync stuff wasn't working but i've fixed that now.

If i used zeromq i wouldn't learn much. I have learnt from this code. Its a success of sorts.
 

ShuggyCoUk

Ars Legatus Legionis
10,388
Subscriptor++
because i'm not rich enough to be able to keep up with the latest and greatest version of visual studio. I'm on 2008.

In no way being harsh here, just honest. If you can't do this then doing it in c# (or for that matter windows) is almost certainly not a good high level design decision.

If you must do this on windows then either work in the express editions (more painful I know) and accept the limitations whilst enjoying the savings or decide if you can afford the ongoing cost of an MSDN subscription.

Being one version behind the curve is generally okay, in deed sometimes sensible while you wait for issues to be ironed out, two is just going to cause you pain.
 

Wraith

Ars Tribunus Militum
1,712
In my day job i have to write new vb6 programs. Vs 2008 really isn't as far behind the curve as it could be.

Apart from ease of use do the new langauge keywords help me understand all this? because that was one of my goals. I'm not a fan of having complicated things hidden from me. Once i understand them and can reason about their performance limits and uses i'm fine with hiding but feel i should understand something if i'm going to use it, there are too many people who just assume the runtime and libraries will do magic for them. Threading can be hard but i should know how to do it right without having to have the nuts and bolts hidden behind the curtain so i don't screw it up.

Updating is probably a good idea and it is something i've looked into. The prices are ridiculous though and it isn't something i can just do at a whim. For the moment what i have is entirely adequate to play around with the things i want to. I've started looking into WCF which prompted me considering moving to the 4.0 runtime but that will take some time.
 

ronelson

Ars Legatus Legionis
21,399
Subscriptor
Being one version behind the curve is generally okay, in deed sometimes sensible while you wait for issues to be ironed out, two is just going to cause you pain.
If someone wants to be cheap about it, that's fine, but then they need to take the time to learn how to program without Visual Studio properly. You don't need VS to make use of the latest version of the CLR, though it's certainly going to require more effort on Wraith's part than using the Express edition will.
 

ShuggyCoUk

Ars Legatus Legionis
10,388
Subscriptor++
I'm not a fan of having complicated things hidden from me.

I suspect you don't really mean that, since the vast majority of modern coding is hiding astonishing levels of complexity from the user (i.e. the programmer). What you likely don't like are:

* Hidden expense
* Hidden interaction with some other aspect of the system

The async/await stuff adds very little expense unless your target scenario is incredibly allocation[1] averse and pre create the required delegates to handle the callbacks implicit in Begin/End APIs. The compiler transforms involved to internally convert to CPS don't add significant costs in the scope of something where you're inherently willing to tolerate context switch level delays.

Using the compiler transforms doesn't alter any of the semantics you are already hitting (which thread you get called back on) and actually helps you in several scenarios (like the message pump thread affinity) by ensuring things happen on the right one largely automatically.

I haven't had to debug it, there may well be considerable additional hassle there (though given MS's previous efforts in that area I would think it's likely not bad).

That's not to say there aren't pitfalls and costs to using it, and I certainly haven't used it enough to feel confident stating you're doing the wrong thing by doing it by hand, but it's not automatically *worse* for hiding complexity.

Think of it a bit like the iterators introduced in c# 2.0. They take something complex and error prone to write by hand (a state machine) and do it for you. They come with two costs:

* Hidden costs: Naive recursive use is asymptotically expensive
This isn't _that_ hidden (there were discussion on this here in the past), but it happens often enough that I consider it likely to hit someone new to it doing a tree traversal at least once.

* Hidden interaction: the lazy aspect kicks in immediately, not just before the first yield return.
It's not overly complex to work round this, but it is something that still occasionally gets me during debugging.

Unless I need an allocation free iteration code path, or it would involve contortions to avoid performing worse in terms of O(n) I would consider it rather bizarre not to use this functionality precisely because it does such a good job at hiding complexity I have no desire to write by hand.

Often the design of the language feature, in the context of the rest of the language, determines how well this works out. C#'s foreach is a classic case of this: loop variable closure capture semantics are the hidden complexity part[2] and for the general[3] case the allocation of the enumerable is the expense. That said when I heard of places that, in the early days, forbade the use of the construct (this was pre-closures so not even that as a rationale) it depressed me no end. The only rational reason at the time for not using them (allocation of the enumerable) implies that you really should only be employing programmers that are capable of understanding the semantics well in the first place!

Aaaaany ways, drifting a bit OT here.

1. really this should be GC pause averse, but it's allocations that drive GC's
2. Fixed as a *source breaking change* in 2012 so another good reason to upgrade. Code snippets on the internet are likely to start relying on the new behaviour.
2. The special cases cover most cases pretty well and now include foreach over the characters in a string.
 

Wraith

Ars Tribunus Militum
1,712
I really do prefer to know how things work, yes some (not nearly all) of the complicated bits it hides from me. Once i understand the mechanisms to a reasonable level i'm pretty happy to take the provided shortcuts.

I'm not a great fan of iterators. I pulled them apart a bit when they were new and was slightly miffed that it generated c# that the compiler wouldn't have allowed me to use. Occasionally i find them helpful but only very occasionally. Similarly i'm not a great fan of linq because hiding behind IEnumerable all the time can lead to some very sloppy and badly performing code. I can use it i just seldom choose to. That may be to do with the domain of problems i work with though because i don't do database things for myself.

Using await etc didn't really cross my mind. Mostly because they're not available in the version of VS i'm using but also because i'm going to have to be mucking about with pinvoke and handles and stuff to get what i want to work and i hadn't thought my way up to the top yet.

I'd got a bit diverted when two ideas that i'd been mulling for a while collided in a single project and decided to have a play. I got stuck and thought i'd ask for help for a change and with a little bit of time spent having to explain the problem the answer became clear as it often does. Next time i might look at await now that i know what i'm trying to do and what the shape of the problems involved are. Now i can solve it the hard way i'll consider the short cut next time if it's available to me.
 
Wraith":1e2cclqd said:
You mean the await and async keywords? if so, because i'm not rich enough to be able to keep up with the latest and greatest version of visual studio. I'm on 2008.
It's free. Just use the latest express edition.

But yes, that's what i'm talking about. I would almost *never* want to write async by directly interacting with those low level building blocks. Instead, i'd just call "await networkStream.WriteAsync(...)" etc. etc. Asynchrony with no muss or fuss. As an added benefit, it works within a loop or exception handling mechanism without having to make that work yourself. Finally, by default you then won't have to deal with anything related to threading (i.e. 'can i access this state from this thread', or 'how should i be marshalling across threads).

Now, if this is about learning the low level goo just so you understand it, then i totally understand. However, if that's not a goal, then i would highly recommend using async/await.
 

Wraith

Ars Tribunus Militum
1,712
I don't think i'd do it often but it's really not all that bad. I rarely tinker with things that move at quite this speed so it's an interesting challenge to debug. It has also helped cement some topics on writing threading related code which i think was helpful.

Since you're here, how would you have done something similar pre-vs2012? Without the use of async/await you'd pretty much have to have used the same thing or a higher level wrapper around it unless i'm missing an entire method of providing this functionality.
 
Wraith":sqbr5flt said:
I don't think i'd do it often but it's really not all that bad. I rarely tinker with things that move at quite this speed so it's an interesting challenge to debug. It has also helped cement some topics on writing threading related code which i think was helpful.

Since you're here, how would you have done something similar pre-vs2012?
I would have used the TPL instead. Prior to that i would likely have done synchronous execution on multiple threads (and only changed that if scalability was a problem).
Without the use of async/await you'd pretty much have to have used the same thing or a higher level wrapper around it unless i'm missing an entire method of providing this functionality.
The TPL makes this fairly trivial. You just wrap it up like so:

Code:
    var task = Task<int>.Factory.FromAsync(
            networkStream.BeginRead, networkStream.EndRead, bytes, 0, bytes.Length, state: null);

...
  
    task.ContinueWith(t => {
       networkStream.Close();  // (if you're done).

       var bytesRead = t.Result;
 
       // Now do something with 'bytes'.
    }, TaskContinuationOptions.OnlyOnRanToCompletion);

    // (also add hte handling for if 'task' didn't complete successfully, etc.

Async/await just make it so i don't have to write out all those lambdas. It also is generally faster as it will execute the logic to bail out early without constructing lambdas if the task is already complete. It will also appropriately set things up so that you get the behavior you want inside a try/catch, etc.

Much more complicated than async/await. But *much* simpler than trying to do everything yourself.
 
Wraith":3br37ps6 said:
Ok, how about pre .net 4, given that i've only got 2008 the highest runtime you can use is 3.5 which i think precludes the TPL.
I'd probably use Rx then. Though i find it not as intuitive to use as the TPL. However, some people find the inverted model to be much easier to use and are absolutely wizards with it :)

There is Observable.FromAsyncPattern that can be used to pair the asynchronous begin/end pair into something easier to use and compose.
 
Status
Not open for further replies.