0.2.1 • Published 6 years ago
net-simulator v0.2.1
net-simulator
simulate terrible internet connections
The public internet is a rough operating environment. There are varying levels of latency, jitter, packet loss, and packet duplication.
When building network protocols, it's important to test implementations against real-world operating conditions.
net-simulator
provides a way to simulate network conditions in a configurable way.
usage
Here is an example of setting up 1 client and 1 server, sending data between them over a simulated internet connection.
You can run this example with npm run example
.
const delay = require('delay')
const sim = require('net-simulator')
function update_peer(peer, time) {
const CLIENT_MAX_RECEIVE_PACKETS = 64
const num_packets_received = sim.network_simulator_receive_packets(peer.network_simulator,
peer.address,
CLIENT_MAX_RECEIVE_PACKETS,
peer.receive_packet_data,
peer.receive_packet_bytes,
peer.receive_from)
if(num_packets_received)
console.log(peer.name, 'received', num_packets_received, 'packets')
for (let i = 0; i < num_packets_received; i++) {
console.log('packet data:', peer.receive_packet_data[i])
console.log('packet bytes:', peer.receive_packet_bytes[i])
// do something with the data...
// destroy the received packet
peer.receive_packet_data[i] = null
}
}
async function main() {
let time = 0 // time elapsed in seconds
const network_simulator = sim.network_simulator_create()
network_simulator.latency_milliseconds = 250
network_simulator.jitter_milliseconds = 250
network_simulator.packet_loss_percent = 5
network_simulator.duplicate_packet_percent = 10
const clientAddress = sim.network_simulator_create_address('ADDRESS_IPV4', '127.0.0.1', 5001)
const serverAddress = sim.network_simulator_create_address('ADDRESS_IPV4', '127.0.0.1', 5002)
const client = {
name: 'client',
network_simulator,
address: clientAddress,
receive_from: serverAddress,
receive_packet_data: [],
receive_packet_bytes: []
}
const server = {
name: 'server',
network_simulator,
address: serverAddress,
receive_from: clientAddress,
receive_packet_data: [],
receive_packet_bytes: []
}
while(true) {
// send message from client to server
const packet_data = new Uint8Array(20)
sim.network_simulator_send_packet(network_simulator, clientAddress, serverAddress, packet_data, packet_data.byteLength)
// send message from server to client
const pd2 = new Uint8Array(15)
sim.network_simulator_send_packet(network_simulator, serverAddress, clientAddress, pd2, pd2.byteLength)
update_peer(client, time)
update_peer(server, time)
sim.network_simulator_update(network_simulator, time)
// for every 3 seconds in real time, advance the network clock by 0.1 seconds
await delay(3000)
time += 0.1
}
}
main()
inspiration & credit
This module is essentially a port of the network simulation logic found in https://github.com/networkprotocol/netcode.io