473,387 Members | 1,790 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

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

.NET Socket

A few days back I was just coding for a basic TCP/IP Client to send and
recieve buffer across network.

I encountered a problem in receiving data through receive method.

I am sharing this with community as it may help others, who are novice is
..NET socket programming.

I searched all over net for samples and found all over (including MSDN).
Blocking mode was enough for me so I coded my receive as:

<CODE>

Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);

</CODE>

But later I noticed that if in last iteration the bytes come to be less than
256 i.e. when I have received all data the next receive call causes the
execution to block as receive has nothing to receive.

Realizing that I changed my code to:

<CODE>

Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes != 256);

</CODE>

It worked fine for all my real scenarios. But I kept thinking that it will
also cause problem if the bytes to be received is multiple of 256 chunks. In
that case it will also block execution when last time it calls receives
method.

Finally I got something better:

<CODE>

Byte[] bytesReceived = new Byte[256];
while (s.Available)
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}

</CODE>

I thought it would be appropriate to change my do-while loop to while. But I
did a mistake there. As sometimes s.Available returns 0 even if receive is
able to receive data. And so in all such cases my loop to recieve data got
bypassed.
As I analyzed this and guessed reason was the data chunk was not available
when s.Available is called but since receive is a blocking call it waits for
data arrival and finally returns with data.

So, finally I changed the code to following and it worked fine.

<CODE>

Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (s.Available);

</CODE>

Regards,
Rahul Anand

Nov 17 '05 #1
6 1447
Rahul Anand <Ra********@discussions.microsoft.com> wrote:
<CODE>

Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);

</CODE>

But later I noticed that if in last iteration the bytes come to be less than
256 i.e. when I have received all data the next receive call causes the
execution to block as receive has nothing to receive.


So the problem you're trying to solve is preventing a call to
Socket.Receive from blocking indefinitely?

If so, you're approaching the problem incorrectly. You should use the
above code in a worker thread, *allowing* it to block indefinitely. You
can call Socket.Shutdown in another thread to interrupt that blocking call.
Nov 17 '05 #2
"=?Utf-8?B?UmFodWwgQW5hbmQ=?=" <Ra********@discussions.microsoft.com>
wrote in news:58**********************************@microsof t.com:
Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (s.Available);


IIRC available returns true on disconnect too and you could get stuck in a loop.

But polling like this is typically very bad if you are using non blocking mode. If you are using
blocking, then Receive will return 0 when disconnected and you need to check for that.

You might also check out Indy - it implements a lot of this stuff automatically for you, and its
free:
http://www.indyproject.org/
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Empower ASP.NET with IntraWeb
http://www.atozed.com/IntraWeb/
Nov 17 '05 #3
"Cool Guy" wrote:
Rahul Anand <Ra********@discussions.microsoft.com> wrote:
<CODE>

Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (bytes > 0);

</CODE>

But later I noticed that if in last iteration the bytes come to be less than
256 i.e. when I have received all data the next receive call causes the
execution to block as receive has nothing to receive.


So the problem you're trying to solve is preventing a call to
Socket.Receive from blocking indefinitely?

If so, you're approaching the problem incorrectly. You should use the
above code in a worker thread, *allowing* it to block indefinitely. You
can call Socket.Shutdown in another thread to interrupt that blocking call.


In my case the blocking mode is fine but I do not want the receive to block
unnecessarily (i.e. it blocks till timeout if there is not data available).

I was just discussing this problem on how to exit the while loop after
receiving all available data.

I hope now it will be more clear now.

Just want to know whether my approach is right or I can do something better.

--
Cheers,
Rahul Anand

Nov 17 '05 #4
> "=?Utf-8?B?UmFodWwgQW5hbmQ=?=" <Ra********@discussions.microsoft.com>
wrote in news:58**********************************@microsof t.com:
Byte[] bytesReceived = new Byte[256];
do
{
bytes = s.Receive(bytesReceived);
strReceived += Encoding.ASCII.GetString(bytesReceived, 0, bytes);
}
while (s.Available);


IIRC available returns true on disconnect too and you could get stuck in a loop.

But polling like this is typically very bad if you are using non blocking mode. If you are using
blocking, then Receive will return 0 when disconnected and you need to check for that.

You might also check out Indy - it implements a lot of this stuff automatically for you, and its
free:
http://www.indyproject.org/
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Empower ASP.NET with IntraWeb
http://www.atozed.com/IntraWeb/


Thanks chad for your comments. I tried to disconnect the server after
sending the request and found it does not cause receive to return zero, it
throws a SocketException. I really want to know whether there is any
situation when recieve returns 0 and Avalible returns some value > 0.

Please post some sample code to achieve this. Your help and time is
appreciated.

--
Cheers,
Rahul Anand
Nov 17 '05 #5
"=?Utf-8?B?UmFodWwgQW5hbmQ=?=" <Ra********@discussions.microsoft.com>
wrote in news:2C**********************************@microsof t.com:
Thanks chad for your comments. I tried to disconnect the server after
sending the request and found it does not cause receive to return
zero, it throws a SocketException. I really want to know whether there
is any situation when recieve returns 0 and Avalible returns some
value > 0.
Winsock returns 0 for sure if its a graceful disconnect. I dont remember what SNS does offhand.
How did you disconnect the server to do this test - a hard disconnect or a soft one?
Please post some sample code to achieve this. Your help and time is
appreciated.


I dont work with SNS directly. I can easily post Indy code if you want. Indy is open source and
therefore free. It will make your code a lot sipmler - Indy provides a much higher abstraction layer
from the network interface, while SNS is just a object wrapper nearly 1:1 for the stack.
--
Chad Z. Hower (a.k.a. Kudzu) - http://www.hower.org/Kudzu/
"Programming is an art form that fights back"

Get your ASP.NET in gear with IntraWeb!
http://www.atozed.com/IntraWeb/
Nov 17 '05 #6


"Chad Z. Hower aka Kudzu" wrote:
"=?Utf-8?B?UmFodWwgQW5hbmQ=?=" <Ra********@discussions.microsoft.com>
wrote in news:2C**********************************@microsof t.com:
Thanks chad for your comments. I tried to disconnect the server after
sending the request and found it does not cause receive to return
zero, it throws a SocketException. I really want to know whether there
is any situation when recieve returns 0 and Avalible returns some
value > 0.


Winsock returns 0 for sure if its a graceful disconnect. I dont remember what SNS does offhand.
How did you disconnect the server to do this test - a hard disconnect or a soft one?


Hi Chad,

I disconnected the server by calling Close method on socket.
I have also referred MSDN on this and there it is written like this:

If no data is available for reading, the Receive method will block until
data is available. If you are in non-blocking mode, and there is no data
available in the in the protocol stack buffer, the Receive method will
complete immediately and throw a SocketException . You can use the Available
property to determine if data is available for reading. __When Available is
non-zero, retry the receive operation__.

If you are using a connection-oriented Socket , the Receive method will read
as much data as is available, up to the size of the buffer. If the remote
host shuts down the Socket connection with the Shutdown method, *and* all
available data has been received, the Receive method will complete
immediately and return zero bytes.

From this I assume till there is data bytes available Receive will not
return 0. And hence Available will work fine.

Your help is appreciated.

--
regards,
Rahul Anand
Nov 17 '05 #7

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

Similar topics

8
by: simon place | last post by:
Spent some very frustrating hours recoding to find a way of closing a server socket, i'd not thought it would be any problem, however, after complete failure and as a last resort, i looked at the...
4
by: DreJoh | last post by:
I've read many articles on the subject and the majority of them give the same solution that's in article 821625 on the MSDN website. I'm using the following code and when a the client disconnects...
6
by: roger beniot | last post by:
I have a program that launches multiple threads with a ThreadStart method like the following (using System.Net.Sockets.Socket for UDP packet transfers to a server): ThreadStart pseudo code: ...
4
by: Chris Tanger | last post by:
Context: C# System.Net.Sockets Socket created with constructor prarmeters Internetwork, Stream and TCP everything else is left at the default parameters and options except linger may be changed...
9
by: Macca | last post by:
Hi, I have a synchronous socket server which my app uses to read data from clients. To test this I have a simulated client that sends 100 byte packets. I have set up the socket server so...
2
by: Macca | last post by:
My app has an asynchronous socket server. It will have 20 clients connected to the server. Each client sends data every 500 millisecondsThe Connections once established will not be closed unless...
0
by: Macca | last post by:
Hi, I am writing an asychronous socket server to handle 20+ simulataneous connections. I have used the example in MSDN as a base. The code is shown at end of question. Each connection has a...
3
by: BuddyWork | last post by:
Hello, Could someone please explain why the Socket.Send is slow to send to the same process it sending from. Eg. Process1 calls Socket.Send which sends to the same IP address and port, the...
5
by: darthghandi | last post by:
I've created a class to listen to all interfaces and do a BeginAccept(). Once it gets a connection, it passes the connected socket off and stores it in a List. Next, it continues to listen for...
4
by: O.B. | last post by:
I have a socket configured as TCP and running as a listener. When I close socket, it doesn't always free up the port immediately. Even when no connections have been made to it. So when I open...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...

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.