Python3 Socket
# Python3.x Python3 Network Programming
Python provides network services at two levels of access:
* Low-level network services support basic Sockets, which provide the standard BSD Sockets API, allowing access to all methods of the underlying operating system's Socket interface.
* High-level network service module SocketServer, which provides server-centric classes to simplify the development of network servers.
* * *
## What is a Socket?
A Socket, also known as a "socket," is typically used by applications to send requests to or respond to network requests, enabling communication between hosts or processes on a single computer.
* * *
## socket() Function
In Python, we use the `socket()` function to create a socket. The syntax is as follows:
socket.socket([family[, type[, proto]]])
### Parameters
* family: The socket family can be AF_UNIX or AF_INET.
* type: The socket type can be `SOCK_STREAM` for connection-oriented or `SOCK_DGRAM` for connectionless.
* proto: Usually left blank, defaults to 0.
### Socket Object (Built-in) Methods
| Function | Description |
| --- | --- |
| Server-side Sockets |
| s.bind() | Binds an address (host, port) to the socket. In AF_INET, the address is represented as a tuple (host, port). |
| s.listen() | Starts TCP listening. The backlog specifies the maximum number of connections the OS can queue before refusing connections. This value should be at least 1, and most applications set it to 5. |
| s.accept() | Passively accepts a TCP client connection (blocking) and waits for the connection to arrive. |
| Client-side Sockets |
| s.connect() | Actively initiates a TCP server connection. The address format is typically a tuple (hostname, port). If the connection fails, it returns a socket.error. |
| s.connect_ex() | An extended version of connect(), returns an error code on failure instead of raising an exception. |
| Common Socket Functions |
| s.recv() | Receives TCP data. Data is returned as a string. bufsize specifies the maximum amount of data to receive. flag provides additional information about the message, usually ignored. |
| s.send() | Sends TCP data. Sends the data in the string to the connected socket. Returns the number of bytes sent, which may be less than the byte size of the string. |
| s.sendall() | Sends TCP data completely. Sends the data in the string to the connected socket, but attempts to send all data before returning. Returns None on success, raises an exception on failure. |
| s.recvfrom() | Receives UDP data. Similar to recv(), but returns a tuple (data, address), where data is the string containing the received data, and address is the socket address of the sender. |
| s.sendto() | Sends UDP data. Sends data to the socket. address is a tuple (ipaddr, port) specifying the remote address. Returns the number of bytes sent. |
| s.close() | Closes the socket. |
| s.getpeername() | Returns the remote address of the connected socket. Typically returns a tuple (ipaddr, port). |
| s.getsockname() | Returns the socket's own address. Typically a tuple (ipaddr, port). |
| s.setsockopt(level, optname, value) | Sets the value of a given socket option. |
| s.getsockopt(level, optname[, buflen]) | Returns the value of a socket option. |
| s.settimeout(timeout) | Sets the timeout period for socket operations. timeout is a float in seconds. A value of None indicates no timeout. Typically, timeouts should be set when the socket is first created, as they may be used for operations like connect(). |
| s.gettimeout() | Returns the current timeout value in seconds. Returns None if no timeout is set. |
| s.fileno() | Returns the socket's file descriptor. |
| s.setblocking(flag) | If flag is False, sets the socket to non-blocking mode; otherwise, sets it to blocking mode (default). In non-blocking mode, if recv() finds no data or send() cannot send data immediately, a socket.error exception is raised. |
| s.makefile() | Creates a file object associated with the socket. |
* * *
## Simple Example
### Server
We use the **socket** function from the socket module to create a socket object. The socket object can be used to set up a socket service by calling other functions.
Now we can specify the service's _port_ by calling the **bind(hostname, port)** function.
Next, we call the socket object's _accept_ method. This method waits for a client connection and returns a _connection_ object, representing the
YouTip