[Mono-list] Newbie seeks clear async socket example

Piers Haken piersh@friskit.com
Tue, 2 Mar 2004 17:01:17 -0800

Here's a simple example of accepting and reading asynchronously from a
socket. It's off the top of my head, so don't expect it to compile/work, but
you should get the general idea...


Socket _sock;

void StartListening (int nPort)
	_sock = new Socket (AddressFamily.InterNetwork, SocketType.Stream,
	_sock.Bind (new IPEndPoint (IPAddress.Any, nPort));
	_sock.Listen (10);
	_sock.BeginAccept (new AsyncCallback (OnAccept), _sock);

void OnAccept (IAsyncResult ar)
	Socket sockCon = sockListen.EndAccept ((Socket) ar.AsyncState);
	new MyConnection ().StartReadingFrom (new NetworkStream (sockCon));

class MyConnection
	byte _rgb = new byte [1024];

	public void StartReadingFrom (Stream stream)
		stream.BeginRead (_rgb, 0, _rgb.Length, new AsyncCallback
(OnReadBytes), stream);
	void OnReadBytes (IAsyncResult ar)
		Stream stream = (Stream) ar.AsyncState;
		int cbRead = stream.EndRead ();
		if (cbRead == 0)
			// connection closed
		// do stuff with bytes...
		StartReadingFrom (stream);

-----Original Message-----
From: mono-list-admin@lists.ximian.com
[mailto:mono-list-admin@lists.ximian.com] On Behalf Of Shaun ONeil
Sent: Tuesday, March 02, 2004 2:45 PM
To: mono-list@lists.ximian.com
Subject: [Mono-list] Newbie seeks clear async socket example

I'm trying to write a simple server listening on a unix socket (ie,
AF_UNIX).  So far the single example I've found is:


..but this method is blocking. I need a connection to be an event I respond
to, not something I sit and wait for. Unfortunately I don't know sockets (or
C#) well enough to make the transition.

Everything else I've found that comes close to readable uses TcpListener,
which I can't seem to press into service as it requires IPEndPoint rather
than UnixEndPoint.

Being unix-specific, I'm having great troubles finding this particular
needle on google .. can anyone here throw me a clear example?

Thanks for your time,

Mono-list maillist  -  Mono-list@lists.ximian.com