import socket
import struct


def tcp_socket_constructor(linger_time=10, tcp_no_delay=1):
    """
    Create a new TCP socket with reasonable socket options set.

    :param linger_time: The linger time after closing the socket to allow buffers to flush. Default: 10
    :type linger_time: int
    :param tcp_no_delay: 1 -> disable Nagle's algorithm on the created socket, 0 -> enable Nagle's algorithm.
        Default: 1
    :type tcp_no_delay: int
    :return: A new TCP socket.
    :rtype socket.socket
    """
    new_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    new_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    new_socket.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack('ii', 1, linger_time))
    # Because everything is sent in a single send call, and we're sending "messages", not really "streams",
    # we turn off Nagle's algorithm to make performance a little better. This might we worth thinking about more though.
    new_socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, tcp_no_delay)
    return new_socket