Skip to content

Instantly share code, notes, and snippets.

@king-11
Last active June 8, 2021 06:20
Show Gist options
  • Save king-11/dc50ba6e3f97b8949a4ec78bbe5cb098 to your computer and use it in GitHub Desktop.
Save king-11/dc50ba6e3f97b8949a4ec78bbe5cb098 to your computer and use it in GitHub Desktop.
Comparing Socket Library of different languages

Socket Libraries

  • Julia
  • Go
  • Python

Julia

Julia uses two types of socket structs one is TCPServer other is TCPSocket similarly we also have UDPSocket

  • TCPSocket is created by calling connect and providing in hostname and port or we can provide valid path for creation of a PipeEndpoint
client = connect(Sockets.IPv4("8.8.8.8"),8000)
  • TCPServer is created by calling listen and providing in addr, port and backlog or we can just like connect provide path to create a PipeServer
server = listen(8080,5)

The hostname is passed in as struct of type IPAddr which is abstract supertype for IP addresses. IPv4 and IPv6 are subtypes of it.

IPv4("8.8.8.8")
ip"127.0.0.1"

TCPServer can accpet TCPSocket or incoming connections by calling in accept with parameter as TCPServer and it returns connection to client stream.

client = accept(server)

The bind function takes in any of the UDP|TCP-Socket|Server, host, port and optional parameter like reuseAddr for allowing multiple threads to bind to same socket.

server = TCPSocket(true)
bind(server,ip"127.0.0.1",8000,reuseaddr=true)

The utility functions include

  • getpeername which returns the IPAddr and Port socket is connected to
  • getsockname is counterpart of getpeername for TCPSocket to return where it is bound
  • getnameinfo performs a reverse-lookup for IP address to return a hostname and service
  • getaddrinfo takes in a host string and type of IPAddr we want it to return IPv4 or IPv6

Above all the functionality seems very similar to other classes but two new features in Julia different from others are:

  • nagle a method to enable or disable Nagle's Algorithm on provided TCP-Socket|Server

    Nagle's Algorithm allows transmission of small packets efficiently by combining a number of small outgoing messages and sending them all at once.

  • quickackis a method to enable or disable Delayed ACK on provided TCP-Socket|Server

    Delayed ACK is also a method for TCP optimization by holding back ACK response for a few milli seconds to allow client to receive multiple data chunks at once

Go Lang

Go has a dedicated net package that provides interface for I/o, TCP/UDP sockets, domain name resolution and Unix domain sockets. It provides support for intutive APIs like listen, dial and accept as well as provides low-level networking primitives too

  • Dial function is used to connect to server its the connect translation present in most languages
    conn, err := net.Dial("tcp", "golang.org:80")
    if err != nil {
    	// handle error
    }
    fmt.Fprintf(conn, "GET / HTTP/1.0\r\n\r\n")
    status, err := bufio.NewReader(conn).ReadString('\n')
    Dial can take parameters for network as "tcp","tcp4","tcp6","udp"....,"ip"....,"unix","unixgram","unixpacket". Address for tcp and udp is of form "host:port" where host can be a literal IP address or name that can resolved and port can be port number or a service name. Dial tries all resolved IP Addresses in order until one succeeds. Go also has a DialTimeout which takes additional timeout parameter where the timeout is spread equally over each consecutive dial for the multiple resolved IPs
  • Listen function is used to create a socket server. the go & call is similar to begin in Chapel
    ln, err := net.Listen("tcp", ":8080")
    if err != nil {
        // handle error
    }
    defer ln.Close()
    for {
        conn, err := ln.Accept()
        if err != nil {
      	  // handle error
        }
        go handleConnection(conn)
    }

Go has a single type for addresses that is IP which is a slice of bytes. while IPv4 takes 4-byte IPv6 takes 16-byte.

fmt.Println(net.IPv4(8, 8, 8, 8))

The Conn is generic type for connections returned after calling Dial it provides access to methods like Read, Write, Close, SetDeadline, etc. All the functions carry an intutive meaning except for SetDeadline which is used to set timer on read and write functions.

The type Listerner is also a generic network listener which provides methods on it like Accept, Close and Addr

Both of the above are generic types whereas Go also has functions like DialTCP, ListenTCp which don't return generic connection and listener instead return TCPConn and TCPListener which provide TCP specific methods for TCP like

  • TCPConn provides methods forclosing read or write ends, setting keep alive and its duration, setting buffer size for read and write
  • TCPListener provides methods like AcceptTCP which returns TCPConn and File method to return a copy of underlying file whose file descriptor is different from connection's

Similarly all other protocols likeUDP, Unix, IP also have their non-generic functions and types.

Python3

Python's approach is very much similar to the C approach on socket programming realated constructs.

The socket module provides socket construct which returns a socket object. The socket constructor takes in all the parameters that C socket takes i.e. family, type, proto and other parameter fileno which will detect other argumetnts from the provided fileno descriptor.

#ipv4 and tcp
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#reconnect to same server
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server_socket.bind((IP, PORT))
#queue length
server_socket.listen()

python also provides higher order constructs just like Go and Julia which are :

  • create_connection : which takes in a tuple (host, port) as address and take optional timeout and source_address for binding a retuns a socket object listening to TCP service. the host is resolved to both AF_INET and AF_INET6
  • create_server: takes in the address tuple, family type which can be either of AF_INET or AF_INET6, takes in the backlog for listen and optional params like reuse_port and dualstack_ipv6

The socket module has methods on it like close, getaddrinfo, gethostbyname, gethostname, htons, htonl, etc which are utility functions

The Socket Object has the some of the follwing standard methods on it that are close, connect, accept, bind, recv, send. The object also provides method to set flags on the socket object, get information about it.

client_socket, client_address = server_socket.accept()

The setblocking method doesn't change the SOCK_NONBLOCK bit on flag insead sets the timeout on blocking operations

client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((IP, PORT))
client_socket.setblocking(False)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment