Giter Site home page Giter Site logo

cevatbarisyilmaz / lossy Goto Github PK

View Code? Open in Web Editor NEW
319.0 5.0 9.0 20 KB

Go package to simulate bandwidth, latency and packet loss for net.PacketConn and net.Conn interfaces

License: MIT License

Go 100.00%
golang go lossy packet-loss latency udp

lossy's Introduction

lossy

GoDoc GitHub release (latest SemVer) GitHub Go Report Card

Go package to simulate bandwidth, latency and packet loss for net.PacketConn and net.Conn interfaces.

Its main usage is to test robustness of applications and network protocols run over unreliable transport protocols such as UDP or IP. As a side benefit, it can also be used as outbound bandwidth limiter.

lossy only alters the writing side of the connection, reading side is kept as it is.

Example

package main

import (
	"fmt"
	"github.com/cevatbarisyilmaz/lossy"
	"log"
	"math/rand"
	"net"
	"time"
)

const packetSize = 64

func main() {
	// Create two connection endpoints over UDP
	packetConn, conn := createConnections()

	// Create a lossy packet connection
	bandwidth := 1048 // 8 Kbit/s
	minLatency := 100 * time.Millisecond
	maxLatency := time.Second
	packetLossRate := 0.33
	headerOverhead := lossy.UDPv4MinHeaderOverhead
	lossyPacketConn := lossy.NewPacketConn(packetConn, bandwidth, minLatency, maxLatency, packetLossRate, headerOverhead)

	// Write some packets via lossy
	var bytesWritten int
	const packetCount = 32
	go func() {
		for i := 0; i < packetCount; i++ {
			packet := createPacket()
			_, err := lossyPacketConn.WriteTo(packet, conn.LocalAddr())
			if err != nil {
				log.Fatal(err)
			}
			bytesWritten += len(packet) + headerOverhead
		}
		fmt.Println("Sent", packetCount, "packets with total size of", bytesWritten, "bytes")
		baseTransmissionDuration := time.Duration(float64(bytesWritten * int(time.Second)) / float64(bandwidth))
		earliestCompletion := baseTransmissionDuration + minLatency
		latestCompletion := baseTransmissionDuration + maxLatency
		fmt.Println("Expected transmission duration is between", earliestCompletion, "and", latestCompletion)
	}()

	// Read packets at the other side
	const timeout = 3 * time.Second
	var packets, bytesRead int
	startTime := time.Now()
	for {
		_ = conn.SetReadDeadline(time.Now().Add(timeout))
		buffer := make([]byte, packetSize)
		n, err := conn.Read(buffer)
		if err != nil {
			break
		}
		bytesRead += n + headerOverhead
		packets++
	}
	dur := time.Now().Sub(startTime) - timeout
	fmt.Println("Received", packets, "packets with total size of", bytesRead, "bytes in", dur)

	// Close the connections
	_ = lossyPacketConn.Close()
	_ = conn.Close()
}

func createConnections() (net.PacketConn, net.Conn) {
	packetConn, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.IPv4(127, 0, 0, 1),
		Port: 0,
	})
	if err != nil {
		log.Fatal(err)
	}
	conn, err := net.DialUDP("udp", nil, packetConn.LocalAddr().(*net.UDPAddr))
	if err != nil {
		log.Fatal(err)
	}
	return packetConn, conn
}

func createPacket() []byte {
	packet := make([]byte, packetSize)
	rand.Read(packet)
	return packet
}

Output

Sent 32 packets with total size of 2944 bytes
Expected transmission duration is between 2.909160305s and 3.809160305s
Received 23 packets with total size of 2116 bytes in 3.2507523s

lossy's People

Contributors

cevatbarisyilmaz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

lossy's Issues

Reordering of packets for PacketConn

Since UDP does not promise anything about ordered delivery, it would be nice to be able to test protocols to make sure they don't rely on packets order.

Though, I am not sure how this would work with bandwidth limitations and latency.

Buffer garbling on write

Since you spawn a goroutine for each send, if the buffers are reused by the application after sending (like in KCP library we use), they will get garbled potentially before sending. I suggest either noting in the documentation that one needs to copy buffers before calling WriteTo() or adding an explicit copy before making a goroutine:

func (c *packetConn) WriteTo(bts []byte, addr net.Addr) (int, error) {
...
  p := make([]byte, len(bts))
  copy(p, bts)
  go func() {
...

https://github.com/cevatbarisyilmaz/lossy/blob/master/packet_conn.go#L69

conn.go has the same issue.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.