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
private.php?do=newpm&u=
sip:(E-Mail Removed)
-=> Sebastian cover-music:
http://ungdomshus.nu <=-