// 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 { public static void Main(string[] args) { Socket original = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); original.Connect(new IPEndPoint(IPAddress.Parse("127.0.0.1"), 50000)); MultiplexingSocket modified = new MultiplexingSocket(original); modified.Send(1, new byte[] { 1 }); modified.Send(2, new byte[] { 2 }); modified.Send(3, new byte[] { 3 }); modified.Send(1, new byte[] { 1, 1 }); modified.Send(2, new byte[] { 2, 2 }); modified.Send(3, new byte[] { 3, 3 }); modified.Send(1, new byte[] { 1, 1, 1 }); modified.Send(2, new byte[] { 2, 2, 2 }); modified.Send(3, new byte[] { 3, 3, 3 }); original.Close(); } } }