473,726 Members | 2,142 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 4492
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.co m

"kuba bogaczewicz" <0x****@gmail.c om> wrote in message
news:11******** **************@ g44g2000cwa.goo glegroups.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.c om> wrote in
message news:uH******** ******@tk2msftn gp13.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.Sock ets;
using System.Threadin g;
using System.Collecti ons;

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(IAsync Result result)
{
Stream s = (Stream)result. AsyncState;
int read;
try
{
read = s.EndRead(resul t);
}
catch
{
s.Close();
throw;
}
Console.WriteLi ne("read: {0}", read);
if ( read == 0 ) // End of stream
s.Close();
else
s.BeginRead(rea dBuf, 0, readBuf.Length, new
AsyncCallback(R eceived), s);
}
static public void Sent(IAsyncResu lt result)
{
TimeSpan waitAmount = TimeSpan.FromSe conds(.1);
Thread.Sleep(wa itAmount);
Stream s = (Stream)result. AsyncState;
if ( sendCount < sendMax )
s.BeginWrite(se ndBuf, 0, sendBuf.Length, new AsyncCallback(S ent), s);
else
s.Close();
sendCount++;
}
static public void Accept(IAsyncRe sult result)
{
Socket s = (Socket)result. AsyncState;
Socket connection;
try
{
connection = s.EndAccept(res ult);
}
catch
{
s.Close();
throw;
}
NetworkStream conncetion_stre am = new NetworkStream(c onnection, true);
conncetion_stre am.BeginRead(re adBuf, 0, readBuf.Length, new
AsyncCallback(R eceived), conncetion_stre am);
}
[STAThread]
static void Main(string[] args)
{
IPEndPoint receiver_ep = new IPEndPoint(IPAd dress.Loopback, 10000 +
new Random().Next() % 1000);
Socket receiver_socket = new
Socket(receiver _ep.Address.Add ressFamily, SocketType.Stre am,
ProtocolType.Tc p);
receiver_socket .Bind(receiver_ ep);
receiver_socket .Listen(100);
receiver_socket .BeginAccept(ne w AsyncCallback(A ccept),
receiver_socket );

IPEndPoint sender_ep = new IPEndPoint(IPAd dress.Loopback,
receiver_ep.Por t+1);
Socket sender_socket = new Socket(sender_e p.Address.Addre ssFamily,
SocketType.Stre am, ProtocolType.Tc p);
sender_socket.B ind(sender_ep);
sender_socket.C onnect(receiver _ep);
Stream sender_stream = new NetworkStream(s ender_socket, true);
sender_stream.B eginWrite(sendB uf, 0, sendBuf.Length, new
AsyncCallback(S ent), sender_stream);

while ( sendCount < sendMax )
{
Thread.Sleep(Ti meSpan.FromSeco nds(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
6342
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 operation". So, I figured it would be useful to post some code about how socket.close() has an implicit send in it and you can actually gain some clarity by being more explicit with the partial close which means splitting socket.close() up into...
5
3683
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 but have been unsuccessful in finding the answers so far. Either because my understanding of sockets isn't where it needs to be or my questions are too basic. My programming environment is Windows XP, Visual Studio .NET 2003 and C#. So here it...
1
3396
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 XP. About the architecture: I have a socket server dll that contains a class that handles connections for a given local ipaddress and port. This class(server) can be started or stopped by calls to the appropriate functions. The server class has...
5
11716
by: mscirri | last post by:
The code below is what I am using to asynchronously get data from a PocketPC device. The data comes in fine in blocks of 1024 bytes but even when I send no data from the PocketPC constant blocks of 1024 with all values set to Null arrive. Other than examine a block of 1024 to see if the entire block is null, is there any other way to determine if , say a chat message "Hi Charlie" has been received completely?
2
15327
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 now see the socket.RecieveTimeout 'property' in the visual studio 2005 help documentation (framework 2.0) and it has example of it being used with TCP socket. This propery is also listed as 'new in .net 2.0'. 1) is the socket.RecieveTimeout...
10
4034
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 anyone please help me with some sample codings and guidance? Can you also suggest some other news group available for socket programming in VB.Net?
11
8610
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 mechanisms. I use a non-blocking approach for this, using the call to 'poll' to support the async mechanism - rather than the 'begin' and 'end' functions. I already found that connecting doesn't set the "isconnected" variable correctly...
0
1900
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 to use the select statement to do only do this periodically. (I'm trying to be a client, accepting data, that might be my first problem) Basically this is the code that im working on to TEST to mimic what the httplib does, only return a socket...
8
4679
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 page_load event, I am using atl com component. Here one for loop is there. In this for loop, number of iterations are 1000, I can receive some data using com component. It is just set of some characters like
3
2766
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: #include "TCPEchoServer.h" /* TCP echo server includes */ #include <pthread.h /* for POSIX threads */
0
8890
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9402
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9259
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9120
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8101
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
4785
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3228
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.