Skip to content

Instantly share code, notes, and snippets.

@dev-ritik
Created December 25, 2019 06:50
Show Gist options
  • Save dev-ritik/5b6d0b17628abcd6c2b79090d77430ec to your computer and use it in GitHub Desktop.
Save dev-ritik/5b6d0b17628abcd6c2b79090d77430ec to your computer and use it in GitHub Desktop.
Simple server program steps

Server

  1. Create a new Socket and get its file descriptor.

    • Domain: Protocol family to be used (AF_INET)
    • Type: Communication strategy (SOCK_STREAM)
    • Protocol: The protocol to be used in the family with the socket type (0)
  2. Set the options for the socket.

    • Level: The level of the options to be set. Use SOL_SOCKET for socket level options
    • Option_name: The name for the option to be passed to the protocol. Options like SO_REUSEADDR shall override checks previous occupation of the same port
    • Option_value: Set the value of the option to the value pointed
  3. Use the sockaddr_in struct to get and store the details of the connection.

    • sin_family: Address family (AF_INET)
    • sin_port: The port to use in 16-bit Network Byte Order (use htons)
    • sin_addr: The IP address in 32-bit Network Byte Order (use INADDR_ANY to connect to any network interface or INADDR_LOOPBACK to connect to 127.0.0.1)
    • sin_zero: Set it to 0
  4. Bind the socket to the IP:port.

    • Address: The interface IP address to bind
    • Port: The port to bind to
  5. Listen to the Socket.

    • Backlog: The maximum length, to which the queue of pending connections not established yet, may grow (1 - 128 (system dependent))

    The Server has been established! and it is listening to incoming requests Now, in an infinite loop,

  6. Accept the first new incoming connection request and create a new socket with the new descriptor referring to it.

    • Address: Details of the connection stored above
  7. As the connection is established, read the data from the file descriptor. Convert the received bytes data to String if required.

    • Count: Read the next count bytes from the file descriptors
    • Buffer: Store them is a buffer to process it
    • Flags: Additional details for reading
  8. Send a message to the client in bytes.

    • Socket: The new connection file descriptor to send the bytes to
    • Message: The message to be sent in bytes
  9. Close the new file descriptor to close the connection.

@dev-ritik
Copy link
Author

⚠️ DO NOT DELETE ⚠️

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment