socket Module API Manual#
Overview#
This module wraps the socket library, allowing users to develop network applications by calling the socket library.
Example#
# Configure tcp/udp socket debugging tool
import socket
import time
PORT = 60000
def client():
# Get IP address and port number
ai = socket.getaddrinfo("10.100.228.5", PORT)
# ai = socket.getaddrinfo("10.10.1.94", PORT)
print("Address Info:", ai)
addr = ai[0][-1]
print("Connect Address:", addr)
# Create socket object
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM, 0)
# Connect to the specified address
s.connect(addr)
for i in range(10):
msg = "K230 TCP client send test {0} \r\n".format(i)
print(msg)
# Send string data
print(s.write(msg))
time.sleep(0.2)
# Close the socket after a 1-second delay
time.sleep(1)
s.close()
print("End")
# Run the client program
client()
API Definitions#
Constructor#
class socket.socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP)
Creates a new socket object using the specified address family (
af), socket type (type), and protocol (proto). Typically, there is no need to explicitly specify theprotoparameter, as MicroPython will automatically select the corresponding protocol type based ontype. Examples:Create a TCP stream socket:
socket(AF_INET, SOCK_STREAM)Create a UDP datagram socket:
socket(AF_INET, SOCK_DGRAM)
Methods#
socket.close()
Closes the socket and releases its associated resources. After closing, all operations on this socket object will fail. When supported by the protocol, the remote end will receive an EOF indication. Although the socket will be automatically closed when garbage collected, it is recommended to explicitly call the
close()method after use.socket.bind(address)
Binds the socket to the specified IP address and port. Ensure the socket is not already bound before calling.
socket.listen([backlog])
Causes the server socket to begin listening for connection requests.
backlogspecifies the maximum number of pending connections, with a minimum of 0 (values less than 0 will be treated as 0). If not specified, the system default value is used.socket.accept()
Accepts a client connection. This method returns
(conn, address), whereconnis a new socket object that can be used to send and receive data on that connection, andaddressis the client’s address.socket.connect(address)
Connects to the specified server socket address.
socket.send(bytes)
Sends data to the socket; the socket must be connected. Returns the number of bytes sent, which may be less than the total length of the data (i.e., a “short write” situation).
socket.sendall(bytes)
Sends complete data to the socket; the socket must be connected. Unlike
send(), this method attempts to continuously send all data until transmission is complete. The behavior of this method on non-blocking sockets is undefined, so it is recommended to use thewrite()method in MicroPython.socket.recv(bufsize)
Receives data from the socket, returning the received data as a bytes object.
bufsizespecifies the maximum number of bytes to receive in a single call.socket.sendto(bytes, address)
Sends data to an unconnected socket, with the destination address specified by
address.socket.recvfrom(bufsize)
Receives data from an unconnected socket, returning
(bytes, address), wherebytesis the received data andaddressis the source address of the data sender.socket.setsockopt(level, optname, value)
Sets socket options.
valuecan be an integer or a bytes-like object.socket.settimeout(value)
Sets the timeout for socket operations (in seconds).
valuecan be a positive number, zero, orNone. If a timeout occurs, the operation will raise anOSError. In non-blocking mode, setvalueto zero; in blocking mode, set it toNone.socket.setblocking(flag)
Sets the blocking mode of the socket. When
flagisFalse, it is in non-blocking mode; whenTrue, it is in blocking mode.socket.makefile(mode=’rb’, buffering=0)
Returns a file object associated with the socket. Only binary modes are supported (such as
rb,wb, andrwb). Thebufferingparameter is ignored in MicroPython.socket.read([size])
Reads data from the socket, returning a bytes object. If
sizeis not specified, reads all available data until EOF.socket.readinto(buf[, nbytes])
Reads data into
buf. Ifnbytesis specified, reads at mostnbytesbytes; otherwise, readslen(buf)bytes.socket.readline()
Reads a line of data from the socket, returning a bytes object.
socket.write(buf)
Writes the data in
bufto the socket. It will attempt to write all data, but for non-blocking sockets, only partial data may be written.socket.error
The
socket.errorexception is not defined in MicroPython; useOSErrordirectly.
