public void StartListening() { try { this.listener = new TcpListener(IPAddress.Any, this.Port); this.Prefix = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}", this.Port)); this.dispatcher = new UriDispatchTables(new Uri(this.Prefix, UrnPrefix)); // Start listening for client requests. this.listener.Start(); // Enter the listening loop while (true) { Logger.Debug("Waiting for a connection..."); // Perform a blocking call to accept requests. var client = this.listener.AcceptTcpClient(); // Get a stream object for reading and writing using (var stream = client.GetStream()) { var acceptedRequest = HttpRequest.ReadFromStreamWithoutClosing(stream); if (string.IsNullOrWhiteSpace(acceptedRequest.StartingLine)) { Logger.Warn("ACCEPTED EMPTY REQUEST"); } else { Logger.Debug("ACCEPTED REQUEST {0}", acceptedRequest.StartingLine); var response = this.HandleRequest(acceptedRequest); using (var writer = new StreamWriter(stream)) { try { writer.Write(response); writer.Flush(); } catch (IOException ex) { Logger.Error("Error occured while writing response: {0}", ex); } } } // Shutdown and end connection } client.Close(); Logger.Debug("Client closed\n"); } } catch (SocketException ex) { Logger.Error("SocketException occurred while trying to start listner: {0}", ex); throw; } catch (ArgumentException ex) { Logger.Error("ArgumentException occurred while trying to start listner: {0}", ex); throw; } finally { // Stop listening for new clients. this.listener.Stop(); } }
public void StartListening() { try { this.listener = new TcpListener(IPAddress.Any, this.Port); this.Prefix = new Uri(string.Format(CultureInfo.InvariantCulture, "http://localhost:{0}", this.Port)); this.dispatcher = new UriDispatchTables(new Uri(this.Prefix, UrnPrefix)); // Start listening for client requests. this.listener.Start(); // Enter the listening loop while (true) { Logger.Debug("Waiting for a connection..."); // Perform a blocking call to accept requests. var client = this.listener.AcceptTcpClient(); // Get a stream object for reading and writing using (var stream = client.GetStream()) { var acceptedRequest = HttpRequest.ReadFromStreamWithoutClosing(stream); Logger.Debug("ACCEPTED REQUEST {0}", acceptedRequest.StartingLine); var response = this.HandleRequest(acceptedRequest); using (var writer = new StreamWriter(stream)) { try { writer.Write(response); writer.Flush(); } catch (IOException ex) { Logger.Error("Error occured while writing response: {0}", ex); } } // Shutdown and end connection } client.Close(); Logger.Debug("Client closed\n"); } } catch (SocketException ex) { Logger.Error("SocketException occurred while trying to start listner: {0}", ex); throw; } catch (ArgumentException ex) { Logger.Error("ArgumentException occurred while trying to start listner: {0}", ex); throw; } finally { // Stop listening for new clients. this.listener.Stop(); } }