The Pico In MicroPython: Sockets |
Written by Mike James & Harry Fairhead | |||||||||||
Monday, 05 August 2024 | |||||||||||
Page 1 of 4 Sockets sound difficult but they are fairly simple. This is an extract from our book all about the Raspberry Pi Pico in MicroPython. Programming the Raspberry Pi Pico/W In MicroPython Second EditionBy Harry Fairhead & Mike JamesBuy from Amazon. Contents
Also of interest: <ASIN:B0BR8LWYMZ> <ASIN:B0BL1HS3QD> Using The Pico W - WiFiThe Pico and the Pico W are very similar and all of the programs presented so far work on both models. The important difference between them is that the Pico W has additional hardware that enables it to use WiFi. From the programming point of view, however, the task is to learn how to use the new WiFi driver and the LwIP library that provides higher-level networking. This is made more difficult than need be by the inadequate documentation provided for both. This will probably improve over time. In this extract we look at how to use sockets. In chapter but not in this extract
SocketsMicroPython supports a limited version of the full Python Sockets module. The parts of the module that are not supported are mostly those concerned with making connections using non-IP networks and hence are generally minor. The most important thing to understand about sockets is that they are a very general way of making a two-way connection between a client and a server. A client can create a socket to transfer data between itself and a server and a server can use a socket to accept a connection from client. The only difference between the two situations is that the server has to either poll or use interrupts to detect a new connection attempt. Before you can start to send and receive data you have to create a socket object: import socket s = socket.socket() This default constructor creates a socket suitable for IPv4 connections. If you want to specify the type of socket being created you have to use: socket(af=AF_INET, type=SOCK_STREAM, proto=IPPROTO_TCP)¶ The af parameter gives the address family and it is either AF_INET for IPv4 or AF_INET6 for IPv6 – at the time of writing only IPv4 is supported. The type parameter indicates either SOCK_STREAM or SOCK_DGRAM,the stream option. The default, SOCK_STREAM, corresponds to the usual TCP/IP connection used to transfer web pages and files in general. It is a persisted and error-corrected connection whereas SOCK_DGRAM sends individual packets without error checking or confirmation that the data was received. The final parameter, proto, sets the exact type of protocol, but as the only two supported are IPPROTO_TCP and IPPROTO_UDP this is set according to the type parameter:
In a more general setting there could be more types of proto supported for each type. |
|||||||||||
Last Updated ( Tuesday, 06 August 2024 ) |