void StopWebServer() { if (mHttpServer != null) { mHttpServer.Stop(); } mHttpServer = null; mOvtServer = new ViewtopServer(); labelHttpsLink.Text = "Stopped"; labelHttpsLink.Enabled = false; labelHttpLink.Text = ""; labelHttpLink.Visible = false; }
void StartWebServer() { if (mHttpServer != null) { return; } Log.Write("Starting web server"); labelHttpsLink.Text = "Starting..."; labelHttpsLink.Enabled = true; labelHttpsLink.Links.Clear(); labelHttpLink.Text = ""; labelHttpLink.Visible = true; labelHttpLink.Links.Clear(); Refresh(); string machineName = ""; try { // Get machine name machineName = Dns.GetHostName(); if (machineName.Trim() == "") { machineName = "localhost"; } if (mSettings.Nickname.Trim() == "") { mSettings.Nickname = machineName; textNickname.Text = machineName; } mOvtServer = new ViewtopServer(); mOvtServer.LocalComputerInfo.ComputerName = machineName; mOvtServer.LocalComputerInfo.Name = mSettings.Nickname; mOvtServer.LocalComputerInfo.HttpsPort = mPortHttps.ToString(); mOvtServer.LocalComputerInfo.HttpPort = mPortHttp.ToString(); // Setup server mHttpServer = new HttpServer(); mHttpServer.HttpHandler += (context) => { var ep = context.LocalEndPoint as IPEndPoint; if (ep != null && ep.Port == mPortForwardToHttps) { var r = context.Response; r.StatusCode = 301; r.StatusMessage = "Moved Permanently"; r.Headers["location"] = "https://" + context.Request.HostNoPort + ":" + mPortHttps + context.Request.Path; return(context.SendResponseAsync("")); } if (context.Request.Path == "/ovt/log") { return(context.SendResponseAsync(Log.GetAsString(200))); } return(mOvtServer.ProcessOpenViewtopRequestAsync(context)); }; // Start servers mHttpServer.Start(new TcpListener(IPAddress.Any, mPortForwardToHttps)); mHttpServer.Start(new TcpListener(IPAddress.Any, mPortHttp)); Log.Write("HTTP web server running"); string link = "http://" + machineName + ":" + mPortHttp; string text = ""; labelHttpLink.Text = "HTTP:" + mPortHttp; labelHttpLink.Links.Add(text.Length, link.Length, link); try { mHttpServer.Start(new TcpListener(IPAddress.Any, mPortHttps), Util.GetCertificate()); Log.Write("HTTPS web server running"); link = "https://" + machineName + ":" + mPortHttps; text = ""; labelHttpsLink.Text = "HTTPS:" + mPortHttps; labelHttpsLink.Links.Add(text.Length, link.Length, link); } catch (Exception ex) { Log.Write("StartWebServer, could not start HTTPS: " + ex.Message); labelHttpsLink.Text = "HTTPS Error"; } } catch (Exception ex) { Log.Write("StartWebServer", ex); try { mHttpServer.Stop(); } catch { } mHttpServer = null; labelHttpsLink.Text = "Error: " + ex.Message; labelHttpLink.Text = ""; throw; } }