Low-Level Networking
local graph
Chapter 19 — Low-Level Networking
Section titled “Chapter 19 — Low-Level Networking”19 Low-Level Networking
Section titled “19 Low-Level Networking”Throughout the book, we have been communicating with different servers and programs using a network protocol. However, understanding how protocols (such as the HTTP protocol) are built can help you understand networking on a deeper level. This does not mean that you should run around implementing your own protocols all the time. However, understanding these protocols on a deeper level will help you understand the trade-offs between different protocols. This awareness will also help you with debugging and understanding why high-level APIs for protocols are the way they are. In this chapter, we will cover the following:
- Building a TCP server
- Implementing HTTP on top of TCP
- Implementing HTTPS on top of TCP
- Exploring WebSockets
By the end of this chapter, you will be able to implement a basic binary protocol on top of a TCP connection and build a TCP server. You will also be able to implement an HTTP and HTTPS protocol on top of the TCP connection. Finally, you will be able to implement a basic WebSocket on top of TCP connections. We also cover an example WebSocket with the Actix API, so you can see how your deeper understanding helps you understand the API reference at a deeper level.
Technical requirements
Section titled “Technical requirements”You can download the example project and code for this book by following the instructions in the Download the example code files section in the Preface of this book.
This chapter’s code files are included in the downloadable code bundle.
Building a TCP server
Section titled “Building a TCP server”TCP connections form the basis of a lot of internet networking protocols. When we create a TCP connection, we can send messages back and forth between the client and server. Connection protocols such as HTTP are built on top of the TCP connection. In this section, we are going to explore TCP connections by building our own binary protocol for a simple key-value store. To achieve this, we are going to utilize a kernel, client, and server with the following file outline: To get our system running, we must carry out the following steps:
- Building a kernel for key-value messages
- Building a TCP server
- Building a TCP client
We can start with the kernel.
Building a kernel for key-value messages
Section titled “Building a kernel for key-value messages”For our message, we are going to serialize our message into a binary stream using bincode. Using bincode makes our code examples simple. However, if the client to the TCP server is not coded in Rust, then our bincode serialization approach will not work, as we are directly serializing Rust data types to bytes. Other serialization protocols, such as JSON, can be used to transfer data between different programming languages.
For our kernel, we need the following Cargo.toml:
## kernel/Cargo.toml[package]name = "kernel"version = "0.1.0"edition = "2021"
[dependencies]bincode = "1.3.3"serde = { version = "1.0.210", features = ["derive"] }With these dependencies, we can now define our key-value message with the following code:
//! kernel/src/lib.rsuse serde::{Serialize, Deserialize};#[derive(Debug, PartialEq, Serialize, Deserialize)]pub enum KvMessage { Get(Vec<u8>), Put((Vec<u8>, Vec<u8>)), Del(Vec<u8>), Success(bool), ReturnValue(Option<Vec<u8>>), Error(String),}Here, we can see that we support some basic key-value operations and some return values, depending on the outcome. We now need to pack our message so that the bytes for the message can be sent over a network, and that the TCP server or client can process the bytes. Our package function takes the following form:
//! kernel/src/lib.rsimpl KvMessage { pub fn package(&self) -> Vec<u8> { let data = bincode::serialize(&self).unwrap(); let len = data.len() as u32; let len_buf = len.to_be_bytes(); let mut buf = Vec::new(); buf.extend_from_slice(&mut len_buf.to_vec()); buf.extend_from_slice(&mut data.to_vec()); buf }}Here, we can see that we serialize the message into a vector of bytes. We then get the length of the vector of bytes and convert that length into byte form using the to_be_bytes function. We then place the length of the data as bytes into the buffer, and then our data. This means that a receiver receiving the message can read the first four bytes to get the length of the data, and then read the data and deserialize it to the message enum to be processed. With this, our kernel is complete and ready to be used by our client and server.
Building a TCP server
Section titled “Building a TCP server”For our server, we need the following dependencies:
# server/Cargo.toml
[package]name = "server"version = "0.1.0"edition = "2021"[dependencies]tokio = { version = "1.40.0", features = ["full"] }kernel = { path = "../kernel" }bincode = "1.3.3"At this point in the book, these dependencies should be understood. For our TCP server exercise, we will put all the code in the main.rs file to keep it simple. For our server, we need the following imports:
//! server/src/main.rsuse tokio::{ io::{ AsyncReadExt, AsyncWriteExt}, net::{TcpListener, TcpStream}};use std::sync::{Arc, Mutex};use std::collections::HashMap;use kernel::KvMessage;The read and write traits are going to be utilized by our TCP stream. All the other structs enable us to perform key-value operations on the state of the server. We can see how the state is constructed with the following code:
//! server/src/main.rs#[tokio::main]async fn main() { let listener = TcpListener::bind( "127.0.0.1:9000" ).await.unwrap(); let state = Arc::new(Mutex::new(HashMap::new())); loop { let (socket, _) = listener.accept().await.unwrap(); let state_ref = state.clone(); tokio::spawn(async move { println!("new connection incoming"); process(socket, state_ref).await; }); }}Here, we can see that we create a TCP listener on port 9000. We then create a hashmap and wrap this hashmap in an Arc and Mutex. The Arc is a pointer that counts the references to that pointer. If the number of references to the pointer becomes zero, then the hashmap is cleaned up. Considering that we are defining our state in the main function, we will always have at least one reference to the state throughout the entire lifetime of the TCP server. The Mutex enables us to lock the data and mutate or directly reference the data inside the Mutex. Both Arc and Mutex are thread-safe, meaning that we can access the state in any thread when processing the key value. This does, however, mean that reads and writes are single-threaded throughout the application, as all threads and async tasks must wait their turn to access the lock for the data. This is not a book on databases, and we are merely using this example to explore custom protocols over TCP. If you want an optimized key-value store, entire packages are designed so you can perform fast reads and writes to a key-value store, such as the following:
- RocksDB: Probably one of the most mature, but it is a Rust wrapper around a C++ key-value store, so it can lead to compilation errors in builds depending on your distribution
- ReDB: A pure Rust implementation of a key-value store that is still young but is actively supported and shows a lot of promise
Now that we have defined our state, we have a loop where we are listening for incoming requests. We then make a clone of our state, which is a reference to the state. Once we have the reference and the connection stream, we spawn a task that processes in incoming message. This process function takes the connection stream and a reference to the state. We can see that the process function is inside an async task that we spawn. This means that our loop can resume, and we can go back to listening to more incoming TCP connections while our message is being processed on the async runtime.
For our process function, we have the following outline:
//! server/src/main.rsasync fn process( mut socket: TcpStream, state: Arc<Mutex<HashMap<Vec<u8>, Vec<u8>>>>) { let mut len_buf = [0; 4]; if socket.read_exact(&mut len_buf).await.is_err() { eprintln!("Failed to read length"); return; } let len = u32::from_be_bytes(len_buf) as usize; println!("Expecting {} bytes", len); let mut buffer = vec![0; len]; if socket.read_exact(&mut buffer).await.is_err() { eprintln!("Failed to read message"); return; } let message: KvMessage = bincode::deserialize(&buffer).unwrap(); let return_message = match message { .. }; let return_message_data = return_message.package();if let Err(e) = socket.write_all(&return_message_data).await { eprintln!("Failed to write to socket; err = {:?}", e);}Here, we read the first four bytes by having a buffer of [0; 4] and passing that buffer into the read_exact function of the TCP stream. We then convert these bytes into a usize. We now have the total number of bytes that we expect from the rest of the stream to get the entire message. We then construct a vector of that size, and then perform another read_exact function of the TCP stream to get the rest of the message. Finally, we deserialize the bytes into a message struct and then process the message, performing a key-value operation on our state. The return message from that operation is then packaged using our package function and written to the stream using the write_all function. For the processing of our incoming message, we have the following code:
//! server/src/main.rslet return_message = match message { KvMessage::Get(key) => { let value = state.lock().unwrap().get(&key).cloned(); KvMessage::ReturnValue(value) }, KvMessage::Put((key, value)) => { state.lock().unwrap().insert(key, value); KvMessage::Success(true) }, KvMessage::Del(key) => { state.lock().unwrap().remove(&key); KvMessage::Success(true) }, _ => { KvMessage::Error("Invalid message type".to_string()) }};Here, we can see that we accept the key-value operation type and return a message that is appropriate, depending on the key-value operation. We can also see that if we receive a message that is supposed to be a return value, we return an error.
Now that our server is built, we can move on to the client.
Building a TCP client
Section titled “Building a TCP client”For our client, we have the same dependencies as the TCP server, as seen here:
[package]name = "client"version = "0.1.0"edition = "2021"[dependencies]tokio = { version = "1.40.0", features = ["full"] }kernel = { path = "../kernel" }bincode = "1.3.3"For our main.rs file, we need the following imports:
//! client/src/main.rsuse tokio::net::TcpStream;use tokio::io::{AsyncReadExt, AsyncWriteExt};use kernel::KvMessage;For our client, we need a function called send_message that carries out the following steps:
- Accept a message and address to the server
- Connect to the server with a TCP stream
- Package the message to be sent
- Send the message over the TCP connection
- Read the first four bytes from the stream to get the length of the data
- Read those bytes from the TCP stream
- Deserialize the bytes from the stream into a message
- Return that message
At this stage, you are in a good position to try and build this function yourself. Now is a good time to stop reading and try and code the send_message function yourself.
If you have attempted to build the function yourself, hopefully, it looks like the following code:
//! client/src/main.rsasync fn send_message(message: KvMessage, addr: &str) -> Result<KvMessage, String> { let mut socket = TcpStream::connect(addr).await.map_err(|e| format!("Failed to connect: {}", e))?; let data = message.package(); socket.write_all(&data).await.map_err(|e| format!("Failed to write to socket: {}", e))?; let mut len_buf = [0; 4]; if socket.read_exact(&mut len_buf).await.is_err() { Ok(KvMessage { data }) } else { Err(format!("Failed to read from socket: {}", len_buf)) }}return Err(“Failed to read length”.to_string());
}let len = u32::from_be_bytes(len_buf) as usize;let mut buffer = vec![0; len];if socket.read_exact(&mut buffer).await.is_err() { return Err("Failed to read message".to_string());}let message: KvMessage = bincode::deserialize(&buffer).map_err( |e| format!("Failed to deserialize message: {}", e) )?;return Ok(message) }
Finally, we can test our send function in our main function with the following code:
//! client/src/main.rs#[tokio::main]async fn main() -> Result<(), String> { println!("{:?}", send_message( KvMessage::Get(b"key".to_vec()), "127.0.0.1:9000" ).await?); println!("{:?}", send_message( KvMessage::Put((b"key".to_vec(), b"value".to_vec())), "127.0.0.1:9000" ).await?); println!("{:?}", send_message( KvMessage::Get(b"key".to_vec()), "127.0.0.1:9000" ).await?); println!("{:?}", send_message( KvMessage::Del(b"key".to_vec()), "127.0.0.1:9000" ).await?); Ok(())}If we run our server, and then our client, our client gives us the following printout:
ReturnValue(None)Success(true)ReturnValue(Some([118, 97, 108, 117, 101]))Success(true)Here, we can see that there is no value initially, then we have success in inserting the value. We can then return the value and then delete the value. Our system works, and we are sending binary messages between the client and the server.
Now that we have become comfortable with TCP, we can move on to building an HTTP request on top of a TCP connection.
Implementing HTTP on top of TCP
Section titled “Implementing HTTP on top of TCP”In this section, we are going to implement a basic HTTP request ourselves using a TCP connection. To explore building our own HTTP request, we need the following layout:
| Cargo.toml | client | Cargo.toml | src | main.rs | http-server | Cargo.toml | src | main.rs |
|---|
First, we are going to define a basic server.
Defining a basic server
Section titled “Defining a basic server”For our server, we create a basic Actix server with the following Cargo.toml file:
## http-server/Cargo.toml[package]name = "http-server"version = "0.1.0"edition = "2021"
[dependencies]actix-web = "4.9.0"serde_json = "1.0.132"serde = { version = "1.0.0", features = ["derive"] }Here, we can see that we are just using the Actix framework with serde for processing JSON bodies. For our basic server, we have the following imports:
//! http-server/src/main.rsuse actix_web::{ web, App, HttpServer, Responder, HttpResponse};use serde::Deserialize;Our JSON body has the following definition:
//! http-server/src/main.rs#[derive(Deserialize, Debug)]struct InputData { message: String,}We handle our incoming requests with the following function:
//! http-server/src/main.rsasync fn post_handler(data: web::Json<InputData>) -> impl Responder { println!("Received: {:?}", data); let response_message = format!( "Received: {}", data.message ); HttpResponse::Ok().json( serde_json::json!({"response": response_message}) )}And finally, the server has the following simple definition:
//! http-server/src/main.rs#[actix_web::main]async fn main() -> std::io::Result<()> { HttpServer::new(|| { App::new() .route("/api/data", web::post().to(post_handler)) }) .bind("127.0.0.1:8080")? .run() .await}Our server is now ready to build an HTTP client from scratch.
Defining an HTTP client from scratch
Section titled “Defining an HTTP client from scratch”For our HTTP client, we are not going to use any dependencies; instead, we are just going to use the standard library. In our main.rs file, we initially have the following imports:
//! client/src/main.rsuse std::io::{Read, Write};use std::net::TcpStream;Inside our main function, we create the TCP stream with the following code:
//! client/src/main.rslet mut stream = TcpStream::connect( "127.0.0.1:8080").expect("Failed to connect to server");We then define our HTTP data to send over the TCP stream with the following code:
//! client/src/main.rslet json_body = r#"{"message": "Hello, Actix!"}"#;let request = format!( "POST /api/data HTTP/1.1\r\n\Host: 127.0.0.1\r\n\Content-Type: application/json\r\n\Content-Length: {}\r\n\Connection: close\r\n\r\n\{}", json_body.len(), json_body);Here, we can see that the HTTP request is a text protocol. The first part is the header, and the method, URI, and HTTP protocol are defined with spaces between them. We then use the delimiter \r\n\ for other values in the header. We can see that we need the content length of the JSON body because the JSON body is at the end of the message, and we need to know the number of bytes to read to get the entire JSON body.
HTTP is basic
The HTTP protocol is known for being basic. It is just text. Because of its basic nature, it has completely dominated web communication. Because it is simple, support for HTTP is everywhere in every browser. I’ve worked on projects where people have tried to get smart with the network protocol they use. Most of the time, their attempts have failed if the network protocol needs to communicate to a client. We cannot know what version of a browser the client is using, or their internet connectivity, and so on. Unless you really need high throughput, then HTTP and HTTPS will be good enough for your application, and you will be able to support most functionality with HTTP and HTTPS.
Now that our message body is defined, we can write our HTTP request to the TCP stream with the following code:
//! client/src/main.rsstream.write_all(request.as_bytes()).unwrap();Now, we need to process the HTTP response. This consists of looping and reading from the stream until we no longer read any bytes. We then have the entire response string. This is achieved with the following code:
//! client/src/main.rslet mut buffer = [0; 512];let mut response = String::new();while let Ok(bytes_read) = stream.read(&mut buffer) { if bytes_read == 0 { break; } response.push_str( &String::from_utf8_lossy(&buffer[..bytes_read]) );}println!("Response: {}", response);And here we have it. If we run our server and then run our client, we get the following printout for the server:
Received: Json(InputData { message: “Hello, Actix!” })
And the following printout for the client:
Response: HTTP/1.1 200 OK content-length: 38 connection: close content-type: application/json date: Sun, 20 Oct 2024 03:10:23 GMT
{“response”:“Received: Hello, Actix!”} We then add the following import to our main.rs file in our server:
//! server/src/main.rsuse openssl::ssl::{SslAcceptor, SslFiletype, SslMethod};Then, our main function takes the following form:
//! server/src/main.rs#[actix_web::main]async fn main() -> std::io::Result<()> { let mut builder = SslAcceptor::mozilla_intermediate( SslMethod::tls() ).unwrap(); builder.set_private_key_file( "key.pem", SslFiletype::PEM ).unwrap(); builder.set_certificate_chain_file( "cert.pem" ).unwrap(); HttpServer::new(|| { App::new() .route("/api/data", web::post().to(post_handler)) }) .bind_openssl("127.0.0.1:8080", builder)? .run() .await}Here, we can see that we define an SSL acceptor. An SSL acceptor is a configuration object that allows the server to handle incoming secure connections. It is responsible for initializing and configuring the SSL/TLS layer when a client connects to the server, ensuring that the communication is encrypted.
Our builder is a mozilla_intermediate. This is a good default. It is not too cutting edge to cut out older out-of-date browsers, but it is up to date enough to not be a security threat. If we were to use the mozilla_modern_v5 at the time of writing this book, the client would require OpenSSL 1.1.1 or LibreSSL 3.4.0 or newer. We then attach a private key to the builder. This private key is used for the encryption of the traffic between the server and client. And then we attach a certificate where we define the identity of the server. As we remember, when we implemented HTTPS in AWS, the certificate was issued by a provider. We will be signing our own certificate, so we will have to bypass security checks and allow our client to connect to our server with our self-signed certificate. Finally, we bind our server to OpenSSL using the bind_openssl function instead of the serve function.
For our key and certificate, we must install openssl. For macOS, we can install using brew with the following command:
brew install opensslFor Linux, you can install openssl with the following command: sudo apt install openssl
For Windows, it is highly suggested that you use the Linux subcommand terminal. However, you could install openssl with Chocolatey with the following command: choco install openssl
Now that we have openssl installed, we can generate our private key with the following command: openssl genrsa -out key.pem 2048
The number is the number of bits that the key has. The bigger the number, the larger the key. The larger the key, the more secure the encryption. However, this increased key size comes at a performance cost.
For our certificate, we create and sign our own with the following command: openssl req -new -x509 -key key.pem -out cert.pem -days 365
The -x509 is the standard for defining the key. The -x509 means that we are telling openssl to generate a self-signed certificate as opposed to making a request for a certificate. openssl will prompt you to fill in a range of different questions about yourself for the certificate. It does not matter what you put, as we are just running this locally. Once the key and certificate are there, we can run our server.
With our server running, we can move on to enabling HTTPS for the client. Our client will need the native TLS in the Cargo.toml file with the following code:
client/Cargo.toml
Section titled “client/Cargo.toml”[dependencies] native-tls = “0.2”
We are going to encrypt our TCP connection with the native-tls crate. Inside our main.rs file, we import the TLS connector with the following code:
//! client/src/main.rsuse native_tls::TlsConnector;We then define the TSL connector with the setting to accept an invalid certificate with the following code:
//! client/src/main.rslet connector = TlsConnector::builder() .danger_accept_invalid_certs(true) .build() .expect("Failed to create TLS connector");We then make the TCP connection, and wrap that connection in the TLS connector with the following code:
//! client/src/main.rslet stream = TcpStream::connect( "127.0.0.1:8080").expect("Failed to connect to server");let mut stream = connector .connect("127.0.0.1", stream) .expect("Failed to establish TLS connection");The rest of the client stays the same. If we run the client, we get the same outcome as we did before, but we have an HTTPS request instead of an HTTP request. And there we have it; we have built an HTTPS protocol on top of our TCP connection. With HTTP protocols covered, we can now move on to WebSockets.
Exploring WebSockets
Section titled “Exploring WebSockets”A WebSocket is a TCP connection where multiple messages are sent back and forth between each other. This can reduce the overhead as we do not need to make new connections every time we need to exchange data. WebSockets are useful for push notifications, live updates, and data feeds, as we can continually push data from the server to the client, or vice versa. As the WebSocket is on top of a TCP connection, we can send any type of message we want. For instance, we can send binary messages or HTTP requests. The main feature of the WebSocket is that the TCP connection remains live, so multiple messages can be sent over that connection.
We can build a basic WebSocket with a simple TCP server and client setup. The overall mechanism is a TCP socket reader that runs in a loop to continuously listen to updates from the WebSocket, as seen in Figure 19.1:
Figure 19.1 - How to listen and process incoming messages over WebSocket
For our server workspace, all we need is Tokio. For our server, we are going to receive a connection and then send a range of numbers. In our main file, our process function merely gets the TCP stream and sends a range of numbers down the stream with the following code:
//! server/src/main.rsuse tokio::{io::AsyncWriteExt, net::{TcpListener, TcpStream}};
async fn process(socket: TcpStream) { let (_, mut writer) = socket.into_split(); for i in 1u32..10 { let bytes = i.to_be_bytes(); }}[figure outside: Figure 19.1]
writer.write_all(&bytes).await.unwrap();}writer.write_all(&[0, 0, 0, 0]).await.unwrap();}At the end of the loop, we will send a zero to the client. In our client, we will treat the zero number as a signal to kill the connection. For the main function of the server, we just listen for incoming connections and spawn an async task with the following code:
//! server/src/main.rs#[tokio::main]async fn main() { let listener = TcpListener::bind( "127.0.0.1:9000" ).await.unwrap(); loop { let (socket, _) = listener.accept().await.unwrap(); tokio::spawn(async move { println!("new connection incoming"); process(socket).await; }); }}For our client, we split the stream into the reader and writer and loop continuously until a zero is sent to the client with the following code:
//! client/src/main.rsuse tokio::net::TcpStream;use tokio::io::AsyncReadExt;
async fn await_messages(addr: &str) -> Result<(), String> { let socket = TcpStream::connect(addr).await.map_err( |e| format!("Failed to connect: {}", e) )?; let (mut reader, _) = socket.into_split(); loop { let mut num_buf = [0; 4]; reader.read_exact(&mut num_buf).await.map_err( |e| format!("Failed to read length: {}", e) )?; let num: usize = u32::from_be_bytes(num_buf).as usize; println!("{:?}", num); }}if num == 0 { break;}Ok(())}#[tokio::main]async fn main() -> Result<(), String> { await_messages("127.0.0.1:9000").await?; Ok(())}If we run the client, we will see that the client prints out the numbers the client receives. These messages could be stock price updates for a dashboard where the JavaScript gets the stock name and price, and then allocates the update for the right component.
While we have written our own basic implementation of a WebSocket, there are plenty of libraries that facilitate WebSockets out of the box. These give you more advantages, such as fragmentation of the messages, framing, bidirectional streaming, and so on. We also should not have to be restricted to only using Tokio directly to handle TCP connections manually for a WebSocket. All major web frameworks support WebSockets. For instance, here is the code from the documentation for Actix on how to handle WebSockets:
async fn echo(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { let (res, mut session, stream) = actix_ws::handle( &req, stream )?; let mut stream = stream .aggregate_continuations() .max_continuation_size(2_usize.pow(20)); rt::spawn(async move { while let Some(msg) = stream.next().await { match msg { Ok(AggregatedMessage::Text(text)) => { session.text(text).await.unwrap(); } Ok(AggregatedMessage::Binary(bin)) => { session.binary(bin).await.unwrap(); } Ok(AggregatedMessage::Ping(msg)) => { session.pong(&msg).await.unwrap(); } } } }) }Here, we can see that we take the HTTP request and the stream, which is the Payload struct. The Payload struct extracts the request’s raw payload stream. This makes sense as we know that the HTTP request is just a protocol sent over TCP. Therefore, Actix is just extracting the TCP stream that the HTTP request was sent over. The documentation code example then spawns an async task with rt::spawn. The rt is Actix’s own async runtime, which is like Tokio. We can see that inside the spawned task, we have a loop waiting for messages. Because WebSocket libraries abstract a lot of manual implementations, we can also see that the WebSocket can handle text or binary data and is handled in frames with the stream.next().await. Frames have headers that have the length of the frame. These frames can also be fragmented, so there is also information around the frame that the packet belongs to, and the order in which the frame is sent. Unless you have very specific needs, it is generally best to use a WebSocket library off the shelf. If you do not want to use a framework such as Actix and you just want to use Tokio, the tokio-tungstenite crate supports WebSockets that connect to Tokio.
Summary
Section titled “Summary”In this chapter, we focused on building custom and basic HTTP protocols on top of TCP connections. We could have just listed all the different APIs for networks and shown how to call them. Instead, we focused on how to build protocols on top of the TCP connection. As we saw with the Actix WebSockets documentation code, we can now understand what is going on under the hood of the API code. It must be stressed that most connection protocols have been defined in web-established third-party dependencies, so while it is useful to know how protocols are built, most of the time, you should use the established dependency, as bugs have been smoothed out, and timeouts, connection attempts, and framing have also been built into these third-party dependencies. In the next chapter, we will build queuing mechanisms.
Questions
Section titled “Questions”-
At a high level, how can you implement a basic binary protocol from a Rust client to a Rust TCP server? This means, how do you structure the message and pack/read that message?
-
At a high level, what is an HTTP request?
-
At a high level, what is a WebSocket?
-
When is it a good idea to use WebSockets?
Answers
Section titled “Answers”-
We can use bincode to serialize the struct, data type, or tuple into a vector of bytes. We then get the length of the vector of bytes and convert the length into four bytes. We then put these four bytes in front of the data. When the receiver is receiving the message, we read the first four bytes and then we convert those four bytes into a number. We then read the number of bytes to get the total message to deserialize.
-
An HTTP request is a text-based message sent over a TCP connection. The HTTP request has a header with information about the request, and a length number if there is a JSON body payload.
-
A WebSocket is a TCP connection that is long-lived, so multiple messages can be sent back and forth between the client and server.
-
WebSockets give us the ability to send multiple updates to and from the client with just one connection. This means that we do not need to make a request to get more information. Instead, a server can send data for the client to use. Applications such as messaging applications and dashboards with live updates are a good use case for WebSockets.
Get this book’s PDF copy, code bundle, and more
Section titled “Get this book’s PDF copy, code bundle, and more”Scan the QR code (or go to packtpub.com/unlock). Search for this book by name, confirm the edition, and then follow the steps on the page.
UNLOCK NOW
Note: Have your invoice handy. Purchases made directly from the Packt website don’t require an invoice.
[blank page]