using System; using System.Net; using System.Net.Sockets; using System.Text; namespace NakedNetwork { using POP3Client; public class NakedNetwork { protected mutable socket : Socket; public this () { socket = null; } public Connect () : void { if (socket != null) Close () else { socket = Socket (AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 120000); socket.SetSocketOption (SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 120000); } } protected Send (toSend : string) : void { // System.Console.WriteLine ("Debug: Send: {0}", toSend); try { ignore (socket.Send (Encoding.ASCII.GetBytes (toSend + "\r\n"))); } catch { | e => throw POP3Client.CommandException (Error.FATALERROR, e.Message); }; } protected Receive (expected : int, ended : string) : string { mutable result = String.Empty; mutable buffer = array (1024); mutable received = 0; mutable retries = 0; mutable expected_ = expected; do { try { received = socket.Receive (buffer, 1024, SocketFlags.None); } catch { | e => throw POP3Client.CommandException (Error.FATALERROR, e.Message); }; if (received == 0) { retries = retries + 1; if (retries >= 100) throw POP3Client.CommandException (Error.FATALERROR, "Socket closed") else {}; } else { result = result + Encoding.ASCII.GetString (buffer, 0, received); expected_ = expected_ - received; }; } while (expected_ < 0 && (received > 0 && !result.EndsWith (ended)) || expected_ > 0 || received == 0); result; } protected Receive (expected : int) : string { Receive (expected, String.Empty); } protected Receive (ended : string) : string { Receive (-1, ended); } protected Receive () : string { Receive (-1); } public Close () : void { if (socket != null && socket.Connected) { socket.Shutdown (SocketShutdown.Send); socket.Close (); } else {}; socket = null; } } }