473,416 Members | 1,463 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,416 software developers and data experts.

C# socket programming

Hello all,
for my school project I have to write a small peer-2-peer application
using Sockets, and I've chosen C# for the task.
I've been doing some research on the topic, and I would really
appreciate if someone checked if I got all things right.

I am going to use asynchronous connections, and here comes some of my
doubts:
-> I want to send each message in a scheme: 4 bytes with the size, then
actual message. According to MSDN I got with VS2003
BeginSend()/EndSend() and BeginReceive/EndReceive will block (in it's
own thread) until the desired amount of data is sent or received. But
I've seen in 'C# Network Programming', that the proper method of
sending would be in a loop checking how much data had been sent, and
resending what is left. Can I trust MSDN on this one - it will be
rather painful to do loop-sending with asynchronous methods, while
having
receive 4 bytes;
receive actual message;
will be quite easy.

-> does BeginSend() puts byte[] with data in some other system queue?
This question is rather essencial to me, because on one Socket
connection I will be sending possibly a couple of files, and also the
same Socket will have to be able to send 'search messages'. Each file
will be sent one part after another, no flooding socket. But durign
that sending user might want to send a 'search' message, and I will
have to do BeginSend() for this one. Can this somehow mess with byte
order sent through the socket?
if on the other side on the connetion application is constantly doing
BeginRecive;
EndReceive;
can this be making problems with buffors on any side?

I'd greatly appreciate quick responses,
thank you in advance

Kuba Bogaczewicz

Nov 17 '05 #1
5 4470
Kuba,

I think you are mistaken about how the async Send and Receive messages
work.

If you call BeginReceive, passing a length of 4, the callback (or
waiting on AsyncWaitHandle) will not return until four bytes have been read,
or some other error occurs.

If you did this asynchronously, you would have one callback for reading
the four bytes. At the end of that callback, you would issue the request
for the bytes in the message (the length of which you now know), and pass it
a callback which would process the message once those bytes are read.

If you only want to read chunks of the message at a time, then you would
have to reissue the call to BeginReceive, and store the bytes that are read
somewhere, until you have enough to process.

Hope this helps.
--
- Nicholas Paldino [.NET/C# MVP]
- mv*@spam.guard.caspershouse.com

"kuba bogaczewicz" <0x****@gmail.com> wrote in message
news:11**********************@g44g2000cwa.googlegr oups.com...
Hello all,
for my school project I have to write a small peer-2-peer application
using Sockets, and I've chosen C# for the task.
I've been doing some research on the topic, and I would really
appreciate if someone checked if I got all things right.

I am going to use asynchronous connections, and here comes some of my
doubts:
-> I want to send each message in a scheme: 4 bytes with the size, then
actual message. According to MSDN I got with VS2003
BeginSend()/EndSend() and BeginReceive/EndReceive will block (in it's
own thread) until the desired amount of data is sent or received. But
I've seen in 'C# Network Programming', that the proper method of
sending would be in a loop checking how much data had been sent, and
resending what is left. Can I trust MSDN on this one - it will be
rather painful to do loop-sending with asynchronous methods, while
having
receive 4 bytes;
receive actual message;
will be quite easy.

-> does BeginSend() puts byte[] with data in some other system queue?
This question is rather essencial to me, because on one Socket
connection I will be sending possibly a couple of files, and also the
same Socket will have to be able to send 'search messages'. Each file
will be sent one part after another, no flooding socket. But durign
that sending user might want to send a 'search' message, and I will
have to do BeginSend() for this one. Can this somehow mess with byte
order sent through the socket?
if on the other side on the connetion application is constantly doing
BeginRecive;
EndReceive;
can this be making problems with buffors on any side?

I'd greatly appreciate quick responses,
thank you in advance

Kuba Bogaczewicz

Nov 17 '05 #2
Nicholas Paldino [.NET/C# MVP] wrote:
Kuba,

I think you are mistaken about how the async Send and Receive messages
work.

If you call BeginReceive, passing a length of 4, the callback (or
waiting on AsyncWaitHandle) will not return until four bytes have been read,
or some other error occurs.

Thank you for that information. That was how I did program it
eventually, but since I'm testing it using localhost, I did not know if
that thing about receiving all or nothing was true.

If you did this asynchronously, you would have one callback for reading
the four bytes. At the end of that callback, you would issue the request
for the bytes in the message (the length of which you now know), and pass it
a callback which would process the message once those bytes are read.
(...)


And it's done that way and it's working :) I'm always interested in
reading whole messages.

Thank you for reply

Kuba Bogaczewicz

Nov 17 '05 #3
kuba bogaczewicz wrote:
Hello all,
for my school project I have to write a small peer-2-peer application
using Sockets, and I've chosen C# for the task.
I've been doing some research on the topic, and I would really
appreciate if someone checked if I got all things right.

I am going to use asynchronous connections, and here comes some of my
doubts:
-> I want to send each message in a scheme: 4 bytes with the size, then
actual message. According to MSDN I got with VS2003
BeginSend()/EndSend() and BeginReceive/EndReceive will block (in it's
own thread) until the desired amount of data is sent or received. But
I've seen in 'C# Network Programming', that the proper method of
sending would be in a loop checking how much data had been sent, and
resending what is left. Can I trust MSDN on this one - it will be
rather painful to do loop-sending with asynchronous methods, while
having
receive 4 bytes;
receive actual message;
will be quite easy.


partially true. BeginSend as well as Send will always either send the
amount of data that is desired or end with an exception.
But Receive and BeginReceive reads 'as much data as is available, up to
the number of bytes specified by the size parameter.'
buu on me, that I found that that late....
and thank god I was testing it with virtual machines :)
responding to myself is not my hobby, just sending it for next
generations, who will have to same question :)

kuba bogaczewicz

Nov 17 '05 #4

"Nicholas Paldino [.NET/C# MVP]" <mv*@spam.guard.caspershouse.com> wrote in
message news:uH**************@tk2msftngp13.phx.gbl...
Kuba,

I think you are mistaken about how the async Send and Receive messages
work.

If you call BeginReceive, passing a length of 4, the callback (or
waiting on AsyncWaitHandle) will not return until four bytes have been
read, or some other error occurs.


This is a common misconception about sockets. In the docs it says:

<quote>
If you are using a connection-oriented Socket, the BeginReceive method will
read as much data as is available, up to the number of bytes specified by
the size parameter.
</quote>

This means that if you pass a length of 4, then it can return anything *up
to* 4 bytes. So in theory, it could return e.g., 2 bytes. In this case
you'll need to call BeginReceive again, this time passing a length of 2 if
you are expecting to receive a total of 4 bytes.

Same logic applies to synchronous Receive.

Regards,
Sami
Nov 17 '05 #5


Nicholas Paldino [.NET/C# MVP] wrote:
I think you are mistaken about how the async Send and Receive messages
work.

If you call BeginReceive, passing a length of 4, the callback (or
waiting on AsyncWaitHandle) will not return until four bytes have been read,
or some other error occurs.


Are you sure about that? The progeam below demonstrates a different
behaviour: that BeginReceive does just like Read: returns the number of
bytes read and 0 for end-of-stream.

====> Testprogram <=====

using System;
using System.IO;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;

class Class1
{
static int sendCount = 0;
static int sendMax = 10;
static byte[] sendBuf = new byte[50];
static byte[] readBuf = new byte[100];
static public void Received(IAsyncResult result)
{
Stream s = (Stream)result.AsyncState;
int read;
try
{
read = s.EndRead(result);
}
catch
{
s.Close();
throw;
}
Console.WriteLine("read: {0}", read);
if ( read == 0 ) // End of stream
s.Close();
else
s.BeginRead(readBuf, 0, readBuf.Length, new
AsyncCallback(Received), s);
}
static public void Sent(IAsyncResult result)
{
TimeSpan waitAmount = TimeSpan.FromSeconds(.1);
Thread.Sleep(waitAmount);
Stream s = (Stream)result.AsyncState;
if ( sendCount < sendMax )
s.BeginWrite(sendBuf, 0, sendBuf.Length, new AsyncCallback(Sent), s);
else
s.Close();
sendCount++;
}
static public void Accept(IAsyncResult result)
{
Socket s = (Socket)result.AsyncState;
Socket connection;
try
{
connection = s.EndAccept(result);
}
catch
{
s.Close();
throw;
}
NetworkStream conncetion_stream = new NetworkStream(connection, true);
conncetion_stream.BeginRead(readBuf, 0, readBuf.Length, new
AsyncCallback(Received), conncetion_stream);
}
[STAThread]
static void Main(string[] args)
{
IPEndPoint receiver_ep = new IPEndPoint(IPAddress.Loopback, 10000 +
new Random().Next() % 1000);
Socket receiver_socket = new
Socket(receiver_ep.Address.AddressFamily, SocketType.Stream,
ProtocolType.Tcp);
receiver_socket.Bind(receiver_ep);
receiver_socket.Listen(100);
receiver_socket.BeginAccept(new AsyncCallback(Accept),
receiver_socket);

IPEndPoint sender_ep = new IPEndPoint(IPAddress.Loopback,
receiver_ep.Port+1);
Socket sender_socket = new Socket(sender_ep.Address.AddressFamily,
SocketType.Stream, ProtocolType.Tcp);
sender_socket.Bind(sender_ep);
sender_socket.Connect(receiver_ep);
Stream sender_stream = new NetworkStream(sender_socket, true);
sender_stream.BeginWrite(sendBuf, 0, sendBuf.Length, new
AsyncCallback(Sent), sender_stream);

while ( sendCount < sendMax )
{
Thread.Sleep(TimeSpan.FromSeconds(1.0));
}
}
}
--
Helge Jensen
mailto:he**********@slog.dk
sip:he**********@slog.dk
-=> Sebastian cover-music: http://ungdomshus.nu <=-
Nov 17 '05 #6

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

Similar topics

1
by: pyguy2 | last post by:
Issues of socket programming can be wierd, so I'm looking for some comments. In my python books I find exclusive use of socket.close(). From my other readings, I know about a "partial close...
5
by: John Sheppard | last post by:
Hi all, I am not sure that I am posting this in the right group but here it goes anyway. I am new to socket programming and I have been searching on the internet to the questions I am about to pose...
1
by: John Sheppard | last post by:
Thanks to everyone that responded to my previous Socket Programming question. Now I have run into some behavior that I don't quite understand. Programming environment. VS.NET 2003, C#, Windows...
5
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...
2
by: djc | last post by:
I read a network programming book (based on framework 1.1) which indicated that you should 'never' use the RecieveTimeout or the SendTimeout 'socket options' on TCP sockets or you may loose data. I...
10
by: Uma - Chellasoft | last post by:
Hai, I am new to VB.Net programming, directly doing socket programming. In C, I will be able to map the message arrived in a socket directly to a structure. Is this possible in VB.Net. Can...
11
by: atlaste | last post by:
Hi, In an attempt to create a full-blown webcrawler I've found myself writing a wrapper around the Socket class in an attempt to make it completely async, supporting timeouts and some scheduling...
0
by: shonen | last post by:
I'm currently attempting to connect to a shoutcast server pull down the information from here and then I'll parse it. I got this working with the httplib, which was great, the problem is I want...
8
by: =?Utf-8?B?Sm9obg==?= | last post by:
Hi all, I am new to .net technologies. ASP.NET supports socket programming like send/receive in c or c++? I am developing web-site application in asp.net and code behind is Visual C#. In...
3
by: Stuart | last post by:
I am in the process of teaching myself socket programming. I am "playing around" with some simple echo server-client programs for m the book TCP/IP Sockets in C. The Server program is: ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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
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,...
0
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...
0
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,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

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.