- Julia
- Go
- Python
Julia uses two types of socket structs one is TCPServer other is TCPSocket similarly we also have UDPSocket
TCPSocketis created by callingconnectand providing inhostnameandportor we can provide validpathfor creation of aPipeEndpoint
client = connect(Sockets.IPv4("8.8.8.8"),8000)TCPServeris created by callinglistenand providing inaddr,portandbacklogor we can just likeconnectprovidepathto create aPipeServer
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
getpeernamewhich returns theIPAddrandPortsocket is connected togetsocknameis counterpart ofgetpeernameforTCPSocketto return where it is boundgetnameinfoperforms a reverse-lookup for IP address to return a hostname and servicegetaddrinfotakes in ahoststring and type ofIPAddrwe want it to returnIPv4orIPv6
Above all the functionality seems very similar to other classes but two new features in Julia different from others are:
naglea method to enable or disable Nagle's Algorithm on providedTCP-Socket|ServerNagle'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 providedTCP-Socket|ServerDelayed 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 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
Dialfunction is used to connect to server its theconnecttranslation present in most languagesconn, 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')
Dialcan 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.Dialtries all resolved IP Addresses in order until one succeeds. Go also has aDialTimeoutwhich takes additional timeout parameter where the timeout is spread equally over each consecutive dial for the multiple resolved IPsListenfunction is used to create a socket server. thego& call is similar tobeginin Chapelln, 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
TCPConnprovides methods forclosingreadorwriteends, settingkeep aliveand its duration, setting buffer size forreadandwriteTCPListenerprovides methods likeAcceptTCPwhich returnsTCPConnandFilemethod 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.
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 optionaltimeoutandsource_addressfor binding a retuns a socket object listening toTCPservice. the host is resolved to bothAF_INETandAF_INET6create_server: takes in theaddresstuple, family type which can be either ofAF_INETorAF_INET6, takes in thebacklogfor listen and optional params likereuse_portanddualstack_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)