All pastes #448732 Raw Edit

Untitled

public text v1 · immutable
·published 2007-04-19 21:02 UTC
rendered paste body
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;

public class MainClass {
	private Socket sock;

	private byte[] buffer = new byte[1024];

	private Queue<byte[]> sendQueue = new Queue<byte[]>();

	private bool sendRunning = false;

	private Timer PingTimer;

	public static void Main() {
		new MainClass().Start(50067);
		new MainClass().Start(50068);
		new MainClass().Start(50069);

		// Wait forever.
		new ManualResetEvent(false).WaitOne();
	}

	public void Start(int port) {
		sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
		sock.BeginConnect("127.0.0.1", port, ConnectCB, null);
	}

	private void ConnectCB(IAsyncResult ar) {
		sock.EndConnect(ar);

		this.Read();
		PingTimer = new Timer(WritePing, new Random(), 100, 100);
	}

	private void WritePing(object o) {
		Random r = (Random) o;

		this.Send(Encoding.ASCII.GetBytes(r.Next().ToString() + Environment.NewLine));
	}

	private void StartSend() {
		lock (sendQueue) {
			if (sendQueue.Count != 0) {
				byte[] data = sendQueue.Dequeue();
				sock.BeginSend(data, 0, data.Length, SocketFlags.None, SendCB, null);
			} else {
				sendRunning = false;
			}
		}
	}

	private void SendCB(IAsyncResult ar) {
		sock.EndSend(ar);
		this.StartSend();
	}

	private void Send(byte[] data) {
		lock (sendQueue) {
			sendQueue.Enqueue(data);

			if (!sendRunning) {
				sendRunning = true;
				this.StartSend();
			}
		}
	}

	private void Read() {
		sock.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, ReadCB, null);
	}

	private void ReadCB(IAsyncResult ar) {
		Console.WriteLine("{0} - {1}", DateTime.Now.ToString(), sock.EndReceive(ar));

		if (sock.Connected)
			this.Read();
	}
}