// Collection of code snippets by Arne Vajhøj // (likely posted to comp.os.vms/INFO-VAX, INFO-TPU, MACRO32, eksperten.dk, newz.dk, LinkedIn or other place sometime between 1990 and now) using System; using System.Collections; using System.Net; using System.Net.Sockets; namespace E { public class MultiplexingSocket { private Socket sock; private Hashtable data; private void Process() { byte[] tmp = new byte[4]; int ix; ix = 0; while((ix += sock.Receive(tmp, ix, tmp.Length - ix, SocketFlags.None)) < 4); int id = BitConverter.ToInt32(tmp, 0); ix = 0; while((ix += sock.Receive(tmp, ix, tmp.Length - ix, SocketFlags.None)) < 4); int len = BitConverter.ToInt32(tmp, 0); byte[] buf = new byte[len]; ix = 0; while((ix += sock.Receive(buf, ix, buf.Length - ix, SocketFlags.None)) < len); if(data[id] == null) { data[id] = buf; } else { byte[] oldbuf = (byte[])data[id]; byte[] combibuf = new byte[oldbuf.Length + buf.Length]; Buffer.BlockCopy(oldbuf, 0, combibuf, 0, oldbuf.Length); Buffer.BlockCopy(buf, 0, combibuf, oldbuf.Length, buf.Length); data[id] = combibuf; } } public MultiplexingSocket(Socket sock) { this.sock = sock; data = new Hashtable(); } public void Send(int id, byte[] b) { sock.Send(BitConverter.GetBytes(id)); sock.Send(BitConverter.GetBytes(b.Length)); sock.Send(b); } public int Receive(int id, byte[] b) { while(data[id] == null) { Process(); } byte[] buf = (byte[])data[id]; if(buf.Length <= b.Length) { Buffer.BlockCopy(buf, 0, b, 0, buf.Length); data.Remove(id); return buf.Length; } else { Buffer.BlockCopy(buf, 0, b, 0, b.Length); byte[] newbuf = new byte[buf.Length - b.Length]; Buffer.BlockCopy(buf, b.Length, newbuf, 0, buf.Length - b.Length); data[id] = newbuf; return b.Length; } } } public class MainClass { private static void Process(MultiplexingSocket modified, int id) { byte[] b = new byte[6]; int total = 0; while(total < b.Length) { int n = modified.Receive(id, b); Console.Write(n + ":"); for(int i = 0; i < n; i++) { Console.Write(" " + b[i]); } Console.WriteLine(); total += n; } } public static void Main(string[] args) { Socket original = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); original.Bind(new IPEndPoint(IPAddress.Any, 50000)); original.Listen(1); MultiplexingSocket modified = new MultiplexingSocket(original.Accept()); Process(modified, 1); Process(modified, 2); Process(modified, 3); original.Close(); } } }