I have a .net 2.0 application that uses the System.Net.Sockets Send() method to send data at regular intervals e.g. every minute. Essentially it is a socket server. Most of the time there will be no clients connected to receive this data but occasionally a user will run an app which will connect to monitor the data that is being sent at regular intervals. At each interval the most I will ever send will be about 1024 bytes with most messages being much smaller.
My question is what impact on system resources does calling Send() every minute with no one to receive it have? Will this eventually eat up all my memory? I have read that the windows sockets are based on Berkeley Sockets which creates a file descriptor. Is there some low level Standard Output (stdout) being performed and the data that does not get received simply goes into a black hole?
what impact on system resources does calling Send() every minute with no one to receive it have?
Should be none - it should throw an error because the socket isn't open.
Will this eventually eat up all my memory?
No, it should simply throw an error.
Is there some low level Standard Output (stdout) being performed and the data that does not get received simply goes into a black hole?
The data is indeed thrown away, and if you're paying attention you'll see the error.
You should first check to see if the socket is open before sending. If no one is connected, don't send. One extra if statement.
-Adam
Related
Good day all!
I am working on a open source server for a game that is closed source - the game operates using TCP/IP sockets (instead of UDP, doh...) So being a connection based protocal, I am contrained to work with this.
My current program structure (dumbed down):
Core Thread
Receive new connection and create a new client object.
Client Object
IOloop (runs on its own thread)
Get data from socket, process packets. (one packet at a time)
Send data buffered from other threads (one packet at a time)
The client will send data immediately (no delay) when it is it's own thread.
I am noticing a huge flaw with the program, mainly it sends data very slow. Because I send data packet by packet, synchronously. (Socket.Send(byte[] buffer))
I would like to send data almost immediately, without delay - asynchronously.
I have tried creating a new thread every time I wanted to send a packet (so each packet sends on it's own managed thread) but this was a huge mess.
My current system uses a synchronous sending with nagle algorithm disabled - but this has the flaw of bottlenecking - send one packet, send operation blocks until TCP to confirms, then send the next... I can issue easily 10 packets every 100ms, and if the packets take 400ms to send, this backs up and breaks. Of course on my Local host I don't get this issue.
So, my question: What would be the best way to send multiple small packets of data? I am thinking of merging the data to send at the end of every IO thread loop to one large byte buffer, to reduce the back and forth delay - but the obvious problem here is this undermines the nagle algorithm avoidance which I had hoped would stop the delays.
How does a synchronous send work? Does it block until the data is confirmed correctly received by the recipient as I believe? Is there a way I can do this without waiting for confirmation? I do understand the packets must all go in order and correctly (as per the protocol specification).
I have done some research and I'm now using the current system:
Async send/receive operations with no threading, using AsyncCallbacks.
So I have the server start a read operation, then callback until done, when a packet is received, it is processed, then a new read operation will begin...
This method drastically reduces system overheads - thread pools, memory etc.
I have used some methods from the following and customised to my liking: https://msdn.microsoft.com/en-us/library/bew39x2a(v=vs.110).aspx
Very efficient, highly recommend this approach. For any TCP/IP network application low lag is very important and async callbacks is the best way to do it.
My goal is to build a c'รจ TCP server that must transmit data that should otherwise be transmitted through UDP, that is unfortunately not an option for me.
The server must transmit a constant stream of realtime data, example: a sequence of numbers
0 1 2 3 4 5 etc... and the client must display only the last one.
If everything goes well the client will receive every number, but if for some reason a packet gets lost I want to detect it and not send it again, but send the latest number instead.
So the question is: is it possible to detect TCP packet loss in C# and clear the buffer without flushing?
Thanks for your time! Fabio Iotti
UPDATE
Dropping all new packets except the lost one is also fine!
UPDATE
Also detecting ack packets whould suffice.
"No."1
At the application level TCP can never have "lost" a packet. It will keep retrying (at the TCP/transport level) such that the application only sees a complete and accurate stream - hence TCP being a "reliable" protocol.
If too many packets are dropped the stream will eventually timeout, but that's about the extent of detecting a failed connection. ("Heartbeats" and throughput monitoring can be used to detect a slow/failing or high-latency connection, but only from a high-level.)
1Some tools like Wireshark can play with TCP streams at a lower abstraction level, but this is generally not fitting (or viable) for application code and is not exposed in the [.NET] TCP/Stream API.
I've begun learning TCP Networking with C#. I've followed the various tutorials and looked at the example code out there and have a working TCP server and client via async connections and writes/reads. I've got file transfers working as well.
Now I'd like to be able to track the progress of the transfer (0% -> 100%) on both the server and the client. When initiating the transfer from the server to client I send the expected file size, so the client knows how many bytes to expect, so I imagine I can easily do: curCount / totalCount on the client. But I'm a bit confused about how to do this for the server.
How accurate can the server tell the transfer situation for the client? Should I guess based on the server's own status (either via the networkStream.BeginWrite() callback, or via the chunk loading from disk and networking writing)? Or should I have the client relay back to the server the client's completion?
I'd like to know this for when to close the connection, as well as be able to visually display progress. Should the server trust the client to close the connection (barring network errors/timeouts/etc)? Or can the server close the connection as soon as it's written to the stream?
There are two distinct percentages of completion here: the client's and the server's. If you consider the server to be done when it has sent the last byte, the server's percentage will always be at least as high as the client's. If you consider the server to be done when the client has processed the last byte the server's percentage will lag the one of the client. No matter what you do you will have differing values on both ends.
The values will differ by the amount of data currently queued in the various buffers between the server app and the client app. This buffer space is usually quite small. AFAIK the maximum TCP window size is by default 200ms of data transfer.
Probably, you don't need to worry about this issue at all because the progress values of both parties will be tightly tied to each other.
Should I guess based on the server's own status (either via the networkStream.BeginWrite() callback, or via the chunk loading from disk and networking writing)?
This is an adequate solution.
Or should I have the client relay back to the server the client's completion?
This would be the 2nd case I described in my 1st paragraph. Also acceptable, although not necessarily a better result and more overhead. I cannot imagine a situation right now in which I'd do it this way.
Should the server trust the client to close the connection (barring network errors/timeouts/etc)?
When one party of a TCP exchange is done sending it should shutdown the socket for sending (using Socket.Shutdown(Send)). This will cause the other party to read zero bytes and know that the transfer is done.
Before closing a socket, it should be shut down. If the Shutdown call completes without error it is guaranteed that the remote party has received all data and that the local party has received all data as well.
Or can the server close the connection as soon as it's written to the stream?
First, shut down, then close. Closing alone does not imply successful transfer.
In this project the protocol is to:
Open Socket
Send Data
Wait for the acknowledgement message or timeout
If ack arrives in the proper window all is well. close the socket
If it times out, close the socket and start over up to N times.
I've noticed in the log that sometimes after the timeout we receive the ack anyway. Since the socket stays open for clean up and stragglers after the close I understand why.
But is there a better way to handle this? I'd like to be sure the connection is really down before reporting something to a line operator.
The timeout right now is an arbitrary value (2.5 seconds) tied to an external timer. It is not in the .Net TCP stack.
The TCP connection isn't really down unless the socket closes on your side. It takes minutes for TCP to decide the connection is down and close the socket if it doesn't receive any response from the network after sending data.
The sockets abstraction layers a bidirectional stream over the TCP channel. The user only sees that the stack has accepted the fragment when Write() (or equivalent) returns successfully, and when Read() returns a non-zero number of characters. The lower levels are opaque. For you to be certain that the server has received and acknowledged your data, you need confirm that the Read() returns the expected amount of data within your allowed time period.
As you have to connect a new session for each request, you have little choice but to tear down the session to make way for the next one. In particular, you can't leave a session around as the server may not allow multiple concurrent connections.
You state that the timeout is 2.5 seconds. If this is much smaller than the message interval, is there a problem if the timeout is extended to something close to the interval. This would appear to be more reliable that hammering away with multiple rapid requests of the same data.
My application is acting as client for a banks server, sending request and getting response from that server. After response processing is done in database which takes some time, so If sever send response in 0.5 second and db operation takes 1 sec after which only my application again try to receive data from server through begin receive then should data will be accumulated somewhere and if yes where it will be stored. Is there will be some limitation so that data will be overflowed and if it happen whether it will closed this socket. I am declaring my socket buffer size to 1024. If anyone also have some article which clear my doubts please share it.
Can you control what the server is sending to you? In most cases when the receiver operates on the received data, sending an application-level ACK upon finishing the work will allow the sender to know when to send the next request. This will ensure no data is lost (since TCP will make sure it does not get lost in the network).
If you can't change the way the server sends you data, you can consider running the receiver in a different thread, where it will save every incoming request to a cache (either only in RAM or to the HD). Then, a worker thread (or multiple threads) will read requests from that cache and do the work you need. This way you will have full control of the buffering of the data.
I think you will read the data in chunks yourself with the Socket - don't you? Than just don't read more than you can handle. The sender should do the same - if your input-buffer overflows the sender should wait before sending more. But maybe there will be an error in this case. If this is really a big issue just start by downloading the data into a file on your disk and process the data after you got all of it. I don't think your HDD will be slower than your network :)