Help me understand

so, im trying to complete codecrafters challenge 'build your own http server'. And I was doing task 'Respond with 200' where i needed to just return 200 code to the client, but it didnt work. After some research I found out that I need to read request data before making a response, but why?
7 Replies
blueberriesiftheywerecats
using System.Net;
using System.Net.Sockets;
using System.Text;

using var server = new TcpListener(IPAddress.Any, 4221);
server.Start();

using var client = server.AcceptTcpClient();

using var s = client.GetStream();

/*
byte[] requestBuffer = new byte[1024];
int bytesRead = s.Read(requestBuffer);
string request = Encoding.UTF8.GetString(requestBuffer, 0, bytesRead);
*/

// wont work without code above

const string msg = "HTTP/1.1 200 OK\r\n\r\n";
byte[] h = Encoding.ASCII.GetBytes(msg);

s.Write(h, 0, h.Length);
using System.Net;
using System.Net.Sockets;
using System.Text;

using var server = new TcpListener(IPAddress.Any, 4221);
server.Start();

using var client = server.AcceptTcpClient();

using var s = client.GetStream();

/*
byte[] requestBuffer = new byte[1024];
int bytesRead = s.Read(requestBuffer);
string request = Encoding.UTF8.GetString(requestBuffer, 0, bytesRead);
*/

// wont work without code above

const string msg = "HTTP/1.1 200 OK\r\n\r\n";
byte[] h = Encoding.ASCII.GetBytes(msg);

s.Write(h, 0, h.Length);
Buddy
Buddy7mo ago
https://www.youtube.com/watch?v=7GBlCinu9yg This is a great video, I suggest you watch it
Computerphile
YouTube
Coding a Web Server in 25 Lines - Computerphile
Just how simple can a web server be? Laurence Tratt, Shopify / Royal Academy of Engineering Research Chair in Language Engineering at Kings College London builds it up. More about Laurie: https://bit.ly/C_LaurenceTratt https://www.facebook.com/computerphile https://twitter.com/computer_phile This video was filmed and edited by Sean Riley. ...
Buddy
Buddy7mo ago
He does not use C# but Rust, however the logic and reasoning remains the same
blueberriesiftheywerecats
he explains that reading stuff?
Buddy
Buddy7mo ago
Computerphile is very educational Oh, I see. I misread your question. You must read it because it is just a single stream of bytes. There aren't two channels like Send and Receive.
blueberriesiftheywerecats
so when Im reading and then writing Im actually just appending my response to that channel? So it now contains both request and response?
Buddy
Buddy7mo ago
From what I have understood, yes.
Want results from more Discord servers?
Add your server