/Finger.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net.Sockets;
using System.Threading;
namespace PullMyFinger {
static class Finger {
public static readonly int FINGER_PORT = 79;
static readonly Regex r = new Regex(@"^(.*)@([a-zA-Z0-9.-]+)$");
public delegate void FingerCallback(string response);
public static string Get(string address) {
Match m = r.Match(address);
if (m.Success) {
Byte[] data;
int bytes;
StringBuilder response = new StringBuilder();
TcpClient client;
client = new TcpClient(m.Groups[2].Value, FINGER_PORT);
data = System.Text.Encoding.ASCII.GetBytes(m.Groups[1].Value + "\r\n");
NetworkStream ns = client.GetStream();
ns.Write(data, 0, data.Length);
data = new Byte[4096];
do {
bytes = ns.Read(data, 0, data.Length);
response.Append(System.Text.Encoding.ASCII.GetString(data, 0, bytes));
} while (bytes > 0);
return response.ToString();
} else {
throw new ArgumentException(address + " is not a valid finger address");
}
}
public static void GetAsync(string address, FingerCallback fcb) {
Thread t = new Thread((ThreadStart)delegate {
// Since we can't really throw these exceptions across threads,
// we just handle them here and return a sensible string result.
string result;
try {
result = Get(address);
} catch (SocketException e) {
result = e.Message;
} catch (ArgumentException e) {
result = e.Message;
}
fcb(result);
});
t.Start();
}
}
}