|
We just demonstrated http. The next section is learning about TCP. TCP is considered a very lightweight protocol, free of the overhead of http. Notice in the code below we require ‘net,’ not ‘http.’ Everything else should look somewhat familiar from before. But let’s be clear. TCP is a transport layer protocol and HTTP is an application layer protocol. HTTP (usually) operates over TCP, so whichever option you choose, it will still be operating over TCP. TCP sockets are more bandwidth efficient, since HTTP contains a whole bunch of extra data (the headers) that would likely not be needed. HTTP is not particularly suited to n-way chat servers. tcpServer.js
var net = require('net'); var tcp_server = net.createServer(function(socket) { socket.write('hello\n'); socket.end('world\n'); }); tcp_server.listen(8000); |
Let’s write a C# program to read those TCP bytes (“Hello World”)
static void Main(string[] args){ TcpClient tcpClient = new TcpClient(); tcpClient.Connect("127.0.0.1", 8000); NetworkStream clientStream = tcpClient.GetStream(); byte[] message = new byte[4096]; int bytesRead; bytesRead = 0; try { // Read up to 4096 bytes bytesRead = clientStream.Read(message, 0, 4096); } catch { /*a socket error has occured*/ } //We have read the message. ASCIIEncoding encoder = new ASCIIEncoding(); Console.WriteLine(encoder.GetString(message, 0, bytesRead)); tcpClient.Close();}
|
Here is the TCP client reading and displaying the bytes. |