NetStream - Typed streams for Rust client/server TCP and UDP networking
NetStream is a Rust library that provides networking abstractions for typed TCP and UDP streams. It simplifies the process of writing server and client implementations that can send and receive data over a network in a type-safe way.
With NetStream, you can define the messages that your server and client will send and receive using Rust structs. The library handles all the low-level networking details, so you can focus on writing high-level, type-safe code that's easy to reason about. Framing and serialization is handled automatically. Currently, messages are serialized with bincode, but this is an implementation detail subject to change.
NetStream can be used to build multiplayer games, distributed systems, or anything in between. This is currently a hobby project and is not recommended for production use. That being said, feedback, contributions, and bug reports from the community are welcome.
Usage
To get started with NetStream, first define your message types by implementing the net_stream::MessageTypes
trait for a struct:
;
// These types represent the messages sent and received over TCP and UDP, respectively.
TcpToServer
represents the message type sent from the client (peer) to the server over TCP. In this example, it has a single variant Message(String)
, which represents a chat message sent by the client.
TcpFromServer
represents the message type sent from the server to the client (peer) over TCP.
In this example, it's an enum to represent different events occurring on a chat server, such as a new user connecting or a new message.
Create structs for the WelcomeMessage
and User
types.
By defining these message types and implementing the net_stream::MessageTypes
trait, you create a typed interface for your server and client implementations. Serialization and framing is handled for you automatically.
Usage: Server
Start server:
let config = default;
let = .await?;
Handle events in a loop:
// Main server loop.
while let Some = events.next.await
Use the server_handle
to perform actions, like sending messages to connected clients:
// Send a message to a single connected client on TCP.
server_handle.message_peer_tcp;
Or sending a message to all connected clients:
// Broadcast a message to all connected clients
server_handle.announce_tcp;
Usage: Client
Connect to the server:
let = .await?;
Handle messages received from the server:
while let Some = events.next.await
Use the handle
to send messages to the server:
if let Err = handle.send_message_tcp
See examples for further details.