public static (int, string) OpenUrl(GopherUri guri) { string response = ""; int status = -1; TcpClient client; try { client = new TcpClient(guri.Host, guri.Port); } catch (Exception ex) { response = ex.Message; status = 100; return(status, response); } client.ReceiveTimeout = client.SendTimeout = CLIENT_TIMEOUT_MS; using (NetworkStream stream = client.GetStream()) { try { string request = guri.Path; if (!request.Contains("\n")) { request += "\n"; } byte[] requestBytes = Encoding.ASCII.GetBytes(request); stream.Write(requestBytes, 0, requestBytes.Length); } catch (Exception ex) { response = ex.Message; status = 200; return(status, response); } Thread.Sleep(SLEEP_BETWEEN_REQ_RESP_MS); try { MemoryStream mem = ReadResponse(stream); if (mem.Length > 0) { response = Encoding.ASCII.GetString(mem.ToArray()); status = 0; } } catch (Exception ex) { response = ex.Message; status = 300; return(status, response); } } return(status, response); }
static void Main(string[] args) { Console.WriteLine("Dipper. The sharp# Gopher browser."); bool run = true; while (run) { Console.Write("> "); string address = Console.ReadLine(); if (string.IsNullOrWhiteSpace(address)) { break; } GopherUri guri; try { guri = GopherUri.Parse(address); } catch { Console.WriteLine(">>> ERROR! Wrong URL!"); continue; } (int status, string response) = Downloader.OpenUrl(guri); if (status == 0) { #if DEBUG string logFilename = $"log-{guri.Host}-{Environment.TickCount}.txt"; File.WriteAllText(logFilename, response); #endif if (guri.ItemType == GopherItemType.SubmenuDir) { Parser.DrawMenu(response); } else { Console.WriteLine(response); } } else { Console.WriteLine($">>> ERROR {status}!"); Console.WriteLine(response); } } }
public static GopherUri Parse(string raw) { if (!raw.StartsWith(GopherScheme)) { raw = GopherScheme + raw; } GopherUri guri = new GopherUri(); var uri = new Uri(raw); guri.uri = uri; if (guri.uri.Segments.Length < 2) { guri.Path = uri.AbsolutePath; guri.ItemType = GopherItemType.SubmenuDir; } else { int gtype = uri.Segments[1][0]; if (Enum.IsDefined(typeof(GopherItemType), gtype)) { guri.ItemType = (GopherItemType)gtype; string pathBody = string.Join("", guri.uri.Segments, 2, guri.uri.Segments.Length - 2); if (uri.Segments[1].Length > 2) { guri.Path = $"/{uri.Segments[1].Substring(1)}/{pathBody}"; } else { guri.Path = $"/{pathBody}"; } } else { guri.Path = uri.AbsolutePath; guri.ItemType = GopherItemType.SubmenuDir; } } return(guri); }