# data[].attributes.attachment_link.title
Controlling Robotic Arm using Raspberry PI 3

# data[].attributes.attachment_link.description
This resource explains how to install a Raspberry Pi operating system image on an SD card. You will need another computer with an SD card reader to install the image. We recommend most users download NOOBS, which is designed to be very easy to use.

# data[].attributes.attachment_link.readable_text
Python is a programming language that lets you work quickly and integrate systems more effectively. Learn More

Fundraiser deal on now: Get a discount on PyCharm + all proceeds go to the Python Software Foundation. Ending soon! GET THE DEAL

# data[].attributes.attachment_link.keywords[]
python programming language object oriented web free open source software license documentation download community

# data[].attributes.attachment_link.description
The official home of the Python Programming Language

# data[].attributes.attachment_link.description
Dropbox is a free service that lets you bring your photos, docs, and videos anywhere and share them easily. Never email yourself a file again!

# data[].attributes.attachment_link.description
We've provided some basic examples to help you discover possible uses for your Raspberry Pi and to get started with software available in Raspbian.

# data[].attributes.attachment_link.readable_text
Using the GPIO Zero library makes it easy to get started with controlling GPIO devices with Python.

LED

To control an LED connected to GPIO17, you can use this code:

from gpiozero import LED from time import sleep led = LED(17) while True: led.on() sleep(1) led.off() sleep(1)

Run this in an IDE like Thonny, and the LED will blink on and off repeatedly.

Button

To read the state of a button connected to GPIO2, you can use this code:

from gpiozero import Button from time import sleep button = Button(2) while True: if button.is_pressed: print("Pressed") else: print("Released") sleep(1)

Button functionality includes the properties is_pressed and is_held; callbacks when_pressed, when_released, and when_held; and methods wait_for_press() and wait_for_release.

Button + LED

To connect the LED and button together, you can use this code:

from gpiozero import LED, Button led = LED(17) button = Button(2) while True: if button.is_pressed: led.on() else: led.off()

Alternatively:

from gpiozero import LED, Button led = LED(17) button = Button(2) while True: button.wait_for_press() led.on() button.wait_for_release() led.off()

or:

from gpiozero import LED, Button led = LED(17) button = Button(2) button.when_pressed = led.on button.when_released = led.off

GPIO Zero documentation

Many more GPIO devices are supported by GPIO Zero. See the library's comprehensive documentation at gpiozero.readthedocs.io.

# data[].attributes.attachment_link.description
Using the GPIO Zero library makes it easy to get started with controlling GPIO devices with Python. To control an LED connected to GPIO17, you can use this code: from gpiozero import LED from time import sleep led = LED(17) while True: led.on() sleep(1) led.off() sleep(1) Run this in an IDE like Thonny, and the LED will blink on and off repeatedly.

# data[].attributes.attachment_link.readable_text
Benvenuto nella sezione Raspberry del sito!

Se sei arrivato qui, sicuramente sarai un appassionato di questa fantastica scheda, di tutti i suoi accessori, ma soprattutto di tutte le cose che puoi fare con essa. Bene, in questa pagina troverai tutti i riferimenti alle novità, eventi, articoli e corsi online sul mondo Raspberry.

Ti suggeriamo di inscriverti alla newsletter di Raspberry, in questo modo verrai aggiornato di ogni novità al riguardo!

Mantieniti aggiornato su tutte le novita' di Raspberry!

Iscriviti alla sezione Raspberry del sito! Ti terremo informato su tutte le novità, gli eventi, e i corsi e gli ultimi articoli pubblicati riguardo il linguaggio Raspberry.
[wysija_form id="7″]

The Pi-volution

Questo è il diagramma storico dell'evoluzione delle schede Raspberry Pi

Corsi Raspberry

Stiamo preparando una serie di corsi online per Raspberry.

Corsi disponibili:

Ancora in preparazione

Elenco degli articoli inerenti a Rapberry

Raspberry Board

Hardware

Tutorials

Accessori

PiCamera

Sensori

Software & Applicazioni

Clustering

Programmazione - OpenCV

Raspberry Pi-like boards

Raspberry Pi con altri dispositivi

HOW TO e FAQ in Raspberry

Raspberry

Conosci alcuni pratiche HOW TO da aggiungere alla lista?

Aggiungi un tuo HOW TO alla lista!

# data[].attributes.attachment_link.title
Raspberry section - news, events, posts and courses

# data[].attributes.attachment_link.description
Se sei arrivato qui, sicuramente sarai un appassionato di questa fantastica scheda, di tutti i suoi accessori, ma soprattutto di tutte le cose che puoi fare con essa. Bene, in questa pagina troverai tutti i riferimenti alle novità, eventi, articoli e corsi online sul mondo Raspberry.

# data[].attributes.attachment_link.readable_text
You can't perform that action at this time.

You signed in with another tab or window. You signed out in another tab or window. Reload to refresh your session. Reload to refresh your session.

# data[].attributes.attachment_link.description
You can't perform that action at this time. You signed in with another tab or window. You signed out in another tab or window. Reload to refresh your session. Reload to refresh your session.

# data[].attributes.body
Confronto Arduino Raspberry

# data[].attributes.attachment_link.title
Comparing the Arduino Uno and Raspberry Pi  | AddOhms #7

# data[].attributes.attachment_link.description
Web: http://addohms.com/ep7 Twitter: @addohms On the surface both the Arduino and Raspberry Pi look like the same thing: inexpensive controller boards for electronics projects. However, one is a simple 8-bit controller while the other is a 32-bit single board computer.

# data[].attributes.attachment_link.description
A sampler of companion videos and excerpts from Raspberry Pi Cookbook by Simon Monk.

# data[].attributes.attachment_link.title
Arduino VS Raspberry ITA Analogie e Differenze

# data[].attributes.attachment_link.title
Help Guides and Resources - How to Use Raspberry Pi

# data[].attributes.attachment_link.description
Helpful resources, videos and guides for getting started with your Raspberry Pi. This is also where you'll find documentation for more advanced material.

# data[].attributes.attachment_link.title
Help Guides and Resources - How to Use Raspberry Pi

# data[].attributes.attachment_link.description
Helpful resources, videos and guides for getting started with your Raspberry Pi. This is also where you'll find documentation for more advanced material.

# data[].attributes.attachment_link.readable_text
Sometimes you need to access a Raspberry Pi without connecting it to a monitor. Perhaps the Pi is embedded in something like a robot, or you may want to view some information from it from elsewhere. Maybe you simply don't have a spare monitor! You can find more information on accessing your Raspberry Pi remotely here.

Contents

rsync
Synchronise folders between the Pi and another computer using rsync over SSH

# data[].attributes.attachment_link.description
Sometimes you need to access a Raspberry Pi without connecting it to a monitor. Perhaps the Pi is embedded in something like a robot, or you may want to view some information from it from elsewhere. Maybe you simply don't have a spare monitor! You can find more information on accessing your Raspberry Pi remotely here.

# data[].attributes.attachment_link.description
Official documentation for the Raspberry Pi, written by the Raspberry Pi Foundation with community contributions.

# data[].attributes.attachment_link.readable_text
C++ è un linguaggio di programmazione a oggetti tra i più diffusi in svariati ambiti dell'informatica professionale, da quello dello sviluppo mobile agli ambienti scientifici, passando per il gaming e lo sviluppo di GUI. Questa guida fornisce una panoramica completa e dettagliata di tutte le sue funzionalità, partendo dalle basi fino ad arrivare agli argomenti di maggiore dettaglio e complessità.

# data[].attributes.attachment_link.title
Raspberry Pi: cos'è, progetti, tutorial, guida in italiano | Maker HTML.it

# data[].attributes.attachment_link.description
C++ è un linguaggio di programmazione a oggetti tra i più diffusi in svariati ambiti dell'informatica professionale, da quello dello sviluppo mobile agli ambienti scientifici, passando per il gaming e lo sviluppo di GUI. Questa guida fornisce una panoramica completa e dettagliata di tutte le sue funzionalità, partendo dalle basi fino ad arrivare agli argomenti di maggiore dettaglio e complessità.

# data[].attributes.attachment_link.title
37 SENSOR KIT TUTORIAL FOR UNO AND MEGA 2.0.pdf

# data[].attributes.attachment_link.readable_text
Raspberry Pi è un single-board computer, molto utilizzato dai Maker nell'ambito del DIY. In questa guida vedremo come configurarlo ed utilizzarlo per creare applicazioni di vario tipo. Partendo dallo studio della scheda, procederemo con la configurazione e l'installazione del sistema di base, fino ad scoprire le potenzialità offerte da Raspberry Pi dal punto di vista dei Maker.

# data[].attributes.attachment_link.description
Raspberry Pi è un single-board computer, molto utilizzato dai Maker nell'ambito del DIY. In questa guida vedremo come configurarlo ed utilizzarlo per creare applicazioni di vario tipo. Partendo dallo studio della scheda, procederemo con la configurazione e l'installazione del sistema di base, fino ad scoprire le potenzialità offerte da Raspberry Pi dal punto di vista dei Maker.

# data[].attributes.body
FTP Server

# data[].attributes.attachment_link.description
FTP (File Transfer Protocol) can be used to transfer files between a Raspberry Pi and another computer. Although with default program sftp-server of Raspbian the users with sufficient privilege can transfer files or directories, access to the filesystem of the limited users is also required often.

# data[].attributes.attachment_link.readable_text
First, we need to open a program on the Pi to write our code. We're going to use IDLE 2, so go to the top left of your desktop, click Menu, click Programming, and click Python 2(IDLE). You should see a blank text editor with an untitled document. You should not see a console with a shell prompt (ie. '>>>"). IF you do, click File, then New.

The first thing we need to do is import the GPIO module. So, on the first line, type exactly, CaSe sensitive,

import RPi.GPIO as GPIO

this imports the GPIO module
next, we need a command called 'sleep', so write

from time import sleep

next we need to name all of the pins, so set the naming mode by writing

GPIO.setmode(GPIO.BOARD)

this sets the names to board mode, which just names the pins according to the numbers in the middle of the diagram above.

Now we need an output to send our PWM signal on, so write

GPIO.setup(03, GPIO.OUT)

Now setup PWM on pin #3 at 50Hz

pwm=GPIO.PWM(03, 50)

Then start it with 0 duty cycle so it doesn't set any angles on startup

pwm.start(0)

Now, to set the angle of the servo, we need to send a specific signal to it. This can differ from servo to servo, as normally it's from 2.5-12.5%, and on the ones I'm using it's 2-12%. Regardless, it will be a 10% window, so to calculate the duty cycle for your desired angle, divide by 18, then add the lowest available value, in this case 2.

So, for 90 degrees, divide by 18, which is 5, then add 2, and you get 7. So on this servo 7% duty is 90 degrees.

As you can see, this math is not very friendly and would be tedious to do every time you wanted to set an angle, so in order to simplify that we're going to write a function in Python that does the math automatically then sets the angle.

So, first define a function. You can name it whatever you like.

def SetAngle(angle):

	duty = angle / 18 + 2

	GPIO.output(03, True)

	pwm.ChangeDutyCycle(duty)

	sleep(1)

	GPIO.output(03, False)

	pwm.ChangeDutyCycle(0)

Now that probably looks like a lot of confusing code, so let me explain everything I did.

The first line sets up a function called 'SetAngle' that we can call later in the code and give our input as an angle.

The second line (which needs to be indented inside the function) sets a variable equal to our angle divided by 18 and 2 added like I showed above

The third line turns on the pin for output

The fourth line changes the duty cycle to match what we calculated

The fifth line waits 1 second so the servo has time to make the turn. Depending on the speed of your servo you might need longer, or you might not need this long

The sixth line turns off the pin

And the seventh line changes the duty back to 0 so we aren't continuously sending inputs to the servo

Now in your code you can call the function, by writing

SetAngle(90)

to tell the servo to turn to 90 degrees.

So, in your code, call a few angles, and when we run the code we'll see how they run on the servo.

At the end of your code, make sure to write

pwm.stop()

GPIO.cleanup()

And that's it! You now have a code that can set your servo to any angle. Press F5, then save to test your code!

*Note: you may receive an error that says the selected GPIO channels are already in use. This won't affect your project, and you can make the warnings stop appearing by writing "GPIO.setwarnings(False)" to your code.*

# data[].attributes.attachment_link.description
First, we need to open a program on the Pi to write our code. We're going to use IDLE 2, so go to the top left of your desktop, click Menu, click Programming, and click Python 2(IDLE). You should see a blank text editor with an untitled document.

# data[].attributes.attachment_link.readable_text
In addition to stepper motors, there are also small and cheap servo motors. The control of Raspberry Pi servo motors is very simple and thanks to the small size and weight they are used in many areas.
Unlike stepper motors, servomotors can be controlled with a single GPIO.

In this tutorial, I'll show an example of how to use Python to control one or more servo motors.

Required Hardware Parts

Of course, it is possible to supply the servo motor with an external power source, but this only makes sense when using several motors. For that, rechargeable batteries/regular batteries would still be needed.

Setup

In most cases, the colors of the servo are as follows and are connected to the Pi:

Black - comes to GND (pin 6) from the Pi
Red - comes to 3V3 (pin 1) from the Pi
Yellow/Orange - to a free GPIO pin (e.g., GPIO17, pin 11)

If you want to play it safe, you can set a ~ 1kΩ resistor between the data pin (yellow/orange) and the Pi. Normally this is not necessary.

If the servo motor does not rotate correctly, this may also influence the power supply of the Raspberry Pi (just look at the datasheet, what the engine consumes). In such a case an external power source makes sense (usually it is 4 to 6V).

Software for controlling the Raspberry Pi servo motors

Unlike stepper motors, servo motors don't occupy many GPIO pins to command a movement. For this, the rotation is controlled by the length of the pulse.

The angle of the motor is set along the length of the pulse, so PWM is particularly useful, which sends repetitive signals at even intervals (the Raspberry Pi Python library must be installed).

We either start python ( sudo python) or open a new script ( sudo nano servomotor.py) with the following content:

import RPi.GPIO as GPIO
import time

servoPIN = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(servoPIN, GPIO.OUT)

p = GPIO.PWM(servoPIN, 50) # GPIO 17 for PWM with 50Hz
p.start(2.5) # Initialization
try:
  while True:
    p.ChangeDutyCycle(5)
    time.sleep(0.5)
    p.ChangeDutyCycle(7.5)
    time.sleep(0.5)
    p.ChangeDutyCycle(10)
    time.sleep(0.5)
    p.ChangeDutyCycle(12.5)
    time.sleep(0.5)
    p.ChangeDutyCycle(10)
    time.sleep(0.5)
    p.ChangeDutyCycle(7.5)
    time.sleep(0.5)
    p.ChangeDutyCycle(5)
    time.sleep(0.5)
    p.ChangeDutyCycle(2.5)
    time.sleep(0.5)
except KeyboardInterrupt:
  p.stop()
  GPIO.cleanup()

If the servo motor shakes a bit while it is not moving, you can pause the pulse with ChangeDutyCycle(0)

For servo motors and their driver boards, the indication of the period and the duty cycle is usually made in the datasheet. In the example of a MG996R we have the following: The period is 20ms long. In addition, a duty cycle of between 5% and 10% of the period is expected. Thus the pulse duration is between 1ms and 2ms. Usually, servos can rotate between 0 and 180°. So we have to adjust the pulse length in between. A length of 1.5ms (7.5%) thus gives an angle of 90 °. And all at precisely 50x per second (50Hz).

If it bothers you that the servo (SG90) can not rotate 360 °, there is a " hack ".

# data[].attributes.attachment_link.description
In addition to stepper motors, there are also small and cheap servo motors. The control of Raspberry Pi servo motors is very simple and thanks to the small size and weight they are used in many areas. Unlike stepper motors, servomotors can be controlled with a single GPIO.

# data[].attributes.body
GPIO

# data[].attributes.attachment_link.readable_text
The Raspberry Pi GPIO pinout guide.

This GPIO Pinout is an interactive reference to the Raspberry Pi GPIO pins, and a guide to the Raspberry Pi's GPIO interfaces. Pinout also includes hundreds of pinouts for Raspberry Pi add-on boards, HATs and pHATs.

Support Pinout.xyz

If you love Pinout, please help me fund new features and improvements:

Every $1 makes all the difference! Thank you.

pHAT Stack

Pinout has teamed up with Pimoroni to create a prototype board compatibility tool, check it out here!

Explore HATs & pHATs

Check out Pinout's board explorer! Use it to find the pinout for your Raspberry Pi add-on board, or discover new boards. If you manufacture boards, we'd love to add yours too. You can contribute to Pinout.xyz at GitHub.com.

What do these numbers mean?

GPIO - General Purpose Input/Output, aka "BCM" or "Broadcom". These are the big numbers, e.g. "GPIO 22". You'll use these with RPi.GPIO and GPIO Zero.

Physical - or "Board" correspond to the pin's physical location on the header. These are the small numbers next to the header, e.g. "Physical Pin 15".

WiringPi - for Gordon Henderson's Wiring Pi library. These are shown as a tooltip when you mouseover a pin.

Rev 1 Pi - alternate GPIO/BCM numbers for the original, 26-pin model "A" and "B" Pi.

What's the orientation of this pinout?

Pinout depicts pin 1 in the top left corner. Pin 1 is the only pin with a square solder pad, which may only be visible from the underside of your Pi. If you orient your Pi such that you are looking at the top with the GPIO on the right and HDMI port(s) on the left, your orientation will match Pinout.

Graphical Pinout

We've whipped up a simple graphical Raspberry Pi GPIO Pinout. Feel free to print, embed, share or hotlink this image and don't forget to credit us!

# data[].attributes.attachment_link.description
The comprehensive add-on boards & GPIO Pinout guide for the Raspberry Pi

# data[].attributes.attachment_link.title
Raspberry Pi and Ultrasonic HC-SR04 distance sensor

# data[].attributes.attachment_link.title
Python Programmable DIY Robot Arm (1 of 5)

# data[].attributes.attachment_link.readable_text
The name of the robot arm is WoodenArm. It looks very cute!

If you want more detail about WoodenArm,please refer to www.lewansoul.com

Now we can make an introduction about the WoodenArm, let's move on it!

Step 1: Description

LewanSoul-WoodenArm is a wooden robotic arm with powerful performance based on Arduino Nano board. The mechanical structure of the entire robotic arm is made of pure wood. Its appearance is exquisite and compact, and its structural stability is strong. The main control chip it used is the Arduino Nano board. The output is the LFD-01 servo, which can connect multiple modules at the same time. A variety of interesting games can be created based on different sensor modules.

Be the First to Share

Recommendations

Made with Math Contest

Multi-Discipline Contest

Robotics Contest

Step 2: Getting to Know the Parts

This cute WoodenArm has various electronic modules: Acceleration module ADXL-345, Color module APDS-9960, Rotary knob module, LED Display screen, LDF-01 servo.

Besides, based on the Arduino Nano control board, we have developed our own Arduino expansion board in order to have more functional modules, and then using WoodenArm to realize more creativity, better learning programming and experience in the process, bring us happiness. So intelligent WoodenArm has the ability to achieve different gameplay.

Step 4: Body Assembly_2

Required materials:

You need to install a part of the body as shown in the picture.
Only need to fix the small block with the corresponding screw, and then Use a screw to connect the servo and the block and fix it, and then fix the servo and the block together. Pay attention to adjust the tightness. This process tests the hands' ability of 2 stars.

Step 7: Chassis Assembly

Required materials:

Robotic arm body bracket*1

Dupont line*4

Screws* several

Nylon*4

Rotary knob module*4

Arduino Nano control board*1

Expansion board*1

You need to install the chassis as shown in the picture. This part is to fix the rotary knob module to the base with screws. At the same time, it needs to insert the Dupont line on the rotary knob module. Finally, the Arduino Nano control board and Arduino expansion board are screwed in the middle of the four rotary knob modules. This process tests the hands' ability of 4 stars.

Step 9: Design Considerations

There are many metal cars on the market, including our own products. However, with the changes of the times, we have been thinking about how to integrate with the times and echo the themes advocated by the contemporary era. Driven by this idea, we designed the WoodenArm, a wooden car. The car's shell is made of wood, so this shows the theme of environmental protection. In our installation package, the wood used on the base and arm of the trolley is a set, and after perfect cutting, all the components can come in handy thanks to the zero waste after installation. The Arduino Nano control board on the car and our own Arduino expansion board have also made the car more powerful in terms of functionality and more inspiring user creativity. We support all creative ideas. In addition, the appearance of the retro, lightweight, the material does not hurt the hand, easy installation, powerful features make this product unique.

Step 10: Gameplay & Final Remarks

You can use the computer or infrared remote controller to control the Wooden Arm.

You can insert the program into the Arduino Nano control board to control the WoodenArm. You can also modify the program or even create a new one by yourself. In fact, in order to help users better learn about WoodenArm development kit, we have prepared several interesting gameplay for users, helping them to quickly get started with WoodenArm learning(You can refer to our LewanSoul website ).

The next game is waiting for you to create~
Join us soon~

Have fun~

Teacher Notes

Teachers! Did you use this instructable in your classroom?
Add a Teacher Note to share how you incorporated it into your lesson.

# data[].attributes.attachment_link.title
How to Use a Few Pieces of Wood to Assemble Into a Cute and Powerful Wood Robot Arm

# data[].attributes.attachment_link.description
How to Use a Few Pieces of Wood to Assemble Into a Cute and Powerful Wood Robot Arm: The name of the robot arm is WoodenArm. It looks very cute! If you want more detail about WoodenArm,please refer to www.lewansoul.com Now we can make an introduction about the WoodenArm, let's move on it!

# data[].attributes.attachment_link.title
37 SENSOR KIT TUTORIAL FOR UNO AND MEGA 2.0.pdf

# data[].attributes.attachment_link.readable_text
Sockets and the socket API are used to send messages across a network. They provide a form of inter-process communication (IPC). The network can be a logical, local network to the computer, or one that's physically connected to an external network, with its own connections to other networks. The obvious example is the Internet, which you connect to via your ISP.

This tutorial has three different iterations of building a socket server and client with Python:

1. We'll start the tutorial by looking at a simple socket server and client.

2. Once you've seen the API and how things work in this initial example, we'll look at an improved version that handles multiple connections simultaneously.

3. Finally, we'll progress to building an example server and client that functions like a full-fledged socket application, complete with its own custom header and content.

By the end of this tutorial, you'll understand how to use the main functions and methods in Python's socket module to write your own client-server applications. This includes showing you how to use a custom class to send messages and data between endpoints that you can build upon and utilize for your own applications.

The examples in this tutorial use Python 3.6. You can find the source code on GitHub.

Networking and sockets are large subjects. Literal volumes have been written about them. If you're new to sockets or networking, it's completely normal if you feel overwhelmed with all of the terms and pieces. I know I did!

Don't be discouraged though. I've written this tutorial for you. As we do with Python, we can learn a little bit at a time. Use your browser's bookmark feature and come back when you're ready for the next section.

Let's get started!

Background

Sockets have a long history. Their use originated with ARPANET in 1971 and later became an API in the Berkeley Software Distribution (BSD) operating system released in 1983 called Berkeley sockets.

When the Internet took off in the 1990s with the World Wide Web, so did network programming. Web servers and browsers weren't the only applications taking advantage of newly connected networks and using sockets. Client-server applications of all types and sizes came into widespread use.

Today, although the underlying protocols used by the socket API have evolved over the years, and we've seen new ones, the low-level API has remained the same.

The most common type of socket applications are client-server applications, where one side acts as the server and waits for connections from clients. This is the type of application that I'll be covering in this tutorial. More specifically, we'll look at the socket API for Internet sockets, sometimes called Berkeley or BSD sockets. There are also Unix domain sockets, which can only be used to communicate between processes on the same host.

Socket API Overview

Python's socket module provides an interface to the Berkeley sockets API. This is the module that we'll use and discuss in this tutorial.

The primary socket API functions and methods in this module are:

Python provides a convenient and consistent API that maps directly to these system calls, their C counterparts. We'll look at how these are used together in the next section.

As part of its standard library, Python also has classes that make using these low-level socket functions easier. Although it's not covered in this tutorial, see the socketserver module, a framework for network servers. There are also many modules available that implement higher-level Internet protocols like HTTP and SMTP. For an overview, see Internet Protocols and Support.

TCP Sockets

Why should you use TCP? The Transmission Control Protocol (TCP):

Is reliable: packets dropped in the network are detected and retransmitted by the sender.

Has in-order data delivery: data is read by your application in the order it was written by the sender.

In contrast, User Datagram Protocol (UDP) sockets created with socket.SOCK_DGRAM aren't reliable, and data read by the receiver can be out-of-order from the sender's writes.

Why is this important? Networks are a best-effort delivery system. There's no guarantee that your data will reach its destination or that you'll receive what's been sent to you.

Network devices (for example, routers and switches), have finite bandwidth available and their own inherent system limitations. They have CPUs, memory, buses, and interface packet buffers, just like our clients and servers. TCP relieves you from having to worry about packet loss, data arriving out-of-order, and many other things that invariably happen when you're communicating across a network.

In the diagram below, let's look at the sequence of socket API calls and data flow for TCP:

The left-hand column represents the server. On the right-hand side is the client.

Starting in the top left-hand column, note the API calls the server makes to setup a "listening" socket:

A listening socket does just what it sounds like. It listens for connections from clients. When a client connects, the server calls accept() to accept, or complete, the connection.

The client calls connect() to establish a connection to the server and initiate the three-way handshake. The handshake step is important since it ensures that each side of the connection is reachable in the network, in other words that the client can reach the server and vice-versa. It may be that only one host, client or server, can reach the other.

In the middle is the round-trip section, where data is exchanged between the client and server using calls to send() and recv().

At the bottom, the client and server close() their respective sockets.

Echo Client and Server

Now that you've seen an overview of the socket API and how the client and server communicate, let's create our first client and server. We'll begin with a simple implementation. The server will simply echo whatever it receives back to the client.

Echo Server

Here's the server, echo-server.py:

Note: Don't worry about understanding everything above right now. There's a lot going on in these few lines of code. This is just a starting point so you can see a basic server in action.

There's a reference section at the end of this tutorial that has more information and links to additional resources. I'll link to these and other resources throughout the tutorial.

Let's walk through each API call and see what's happening.

socket.socket() creates a socket object that supports the context manager type, so you can use it in a with statement. There's no need to call s.close():

The arguments passed to specify the address family and socket type. AF_INET is the Internet address family for IPv4. SOCK_STREAM is the socket type for TCP, the protocol that will be used to transport our messages in the network.

bind() is used to associate the socket with a specific network interface and port number:

The values passed to bind() depend on the address family of the socket. In this example, we're using socket.AF_INET (IPv4). So it expects a 2-tuple: (host, port).

host can be a hostname, IP address, or empty string. If an IP address is used, host should be an IPv4-formatted address string. The IP address 127.0.0.1 is the standard IPv4 address for the loopback interface, so only processes on the host will be able to connect to the server. If you pass an empty string, the server will accept connections on all available IPv4 interfaces.

port should be an integer from 1- 65535 ( 0 is reserved). It's the TCP port number to accept connections on from clients. Some systems may require superuser privileges if the port is < 1024.

Here's a note on using hostnames with bind():

"If you use a hostname in the host portion of IPv4/v6 socket address, the program may show a non-deterministic behavior, as Python uses the first address returned from the DNS resolution. The socket address will be resolved differently into an actual IPv4/v6 address, depending on the results from DNS resolution and/or the host configuration. For deterministic behavior use a numeric address in host portion." (Source)

I'll discuss this more later in Using Hostnames, but it's worth mentioning here. For now, just understand that when using a hostname, you could see different results depending on what's returned from the name resolution process.

Continuing with the server example, listen() enables a server to accept() connections. It makes it a "listening" socket:

If your server receives a lot of connection requests simultaneously, increasing the backlog value may help by setting the maximum length of the queue for pending connections. The maximum value is system dependent. For example, on Linux, see /proc/sys/net/core/somaxconn.

accept() blocks and waits for an incoming connection. When a client connects, it returns a new socket object representing the connection and a tuple holding the address of the client. The tuple will contain (host, port) for IPv4 connections or (host, port, flowinfo, scopeid) for IPv6. See Socket Address Families in the reference section for details on the tuple values.

One thing that's imperative to understand is that we now have a new socket object from accept(). This is important since it's the socket that you'll use to communicate with the client. It's distinct from the listening socket that the server is using to accept new connections:

After getting the client socket object conn from accept(), an infinite while loop is used to loop over blocking calls to conn.recv(). This reads whatever data the client sends and echoes it back using conn.sendall().

If conn.recv() returns an empty object, b'', then the client closed the connection and the loop is terminated. The with statement is used with conn to automatically close the socket at the end of the block.

Echo Client

Now let's look at the client, echo-client.py:

In comparison to the server, the client is pretty simple. It creates a socket object, connects to the server and calls s.sendall() to send its message. Lastly, it calls s.recv() to read the server's reply and then prints it.

Running the Echo Client and Server

Let's run the client and server to see how they behave and inspect what's happening.

Open a terminal or command prompt, navigate to the directory that contains your scripts, and run the server:

Your terminal will appear to hang. That's because the server is blocked (suspended) in a call:

It's waiting for a client connection. Now open another terminal window or command prompt and run the client:

In the server window, you should see:

Viewing Socket State

To see the current state of sockets on your host, use netstat. It's available by default on macOS, Linux, and Windows.

Here's the netstat output from macOS after starting the server:

Local Address is *.65432, which means all available host interfaces that support the address family will be used to accept incoming connections. In this example, in the call to socket(), socket.AF_INET was used (IPv4). You can see this in the Proto column: tcp4.

I've trimmed the output above to show the echo server only. You'll likely see much more output, depending on the system you're running it on. The things to notice are the columns Proto, Local Address, and (state). In the last example above, netstat shows the echo server is using an IPv4 TCP socket ( tcp4), on port 65432 on all interfaces (*.65432), and it's in the listening state ( LISTEN).

Another way to see this, along with additional helpful information, is to use lsof (list open files). It's available by default on macOS and can be installed on Linux using your package manager, if it's not already:

netstat and lsof have a lot of options available and differ depending on the OS you're running them on. Check the man page or documentation for both. They're definitely worth spending a little time with and getting to know. You'll be rewarded. On macOS and Linux, use man netstat and man lsof. For Windows, use netstat /?.

Here's a common error you'll see when a connection attempt is made to a port with no listening socket:

$ ./echo-client.py
Traceback (most recent call last):
  File "./echo-client.py", line 9, in <module>
    s.connect((HOST, PORT))
ConnectionRefusedError: [Errno 61] Connection refused

Either the specified port number is wrong or the server isn't running. Or maybe there's a firewall in the path that's blocking the connection, which can be easy to forget about. You may also see the error Connection timed out. Get a firewall rule added that allows the client to connect to the TCP port!

There's a list of common errors in the reference section.

Communication Breakdown

Let's take a closer look at how the client and server communicated with each other:

When using the loopback interface (IPv4 address 127.0.0.1 or IPv6 address ::1), data never leaves the host or touches the external network. In the diagram above, the loopback interface is contained inside the host. This represents the internal nature of the loopback interface and that connections and data that transit it are local to the host. This is why you'll also hear the loopback interface and IP address 127.0.0.1 or ::1 referred to as "localhost."

Applications use the loopback interface to communicate with other processes running on the host and for security and isolation from the external network. Since it's internal and accessible only from within the host, it's not exposed.

You can see this in action if you have an application server that uses its own private database. If it's not a database used by other servers, it's probably configured to listen for connections on the loopback interface only. If this is the case, other hosts on the network can't connect to it.

Be careful out there. It's a nasty, cruel world. Be sure to read the section Using Hostnames before venturing from the safe confines of "localhost." There's a security note that applies even if you're not using hostnames and using IP addresses only.

Handling Multiple Connections

"Applications are responsible for checking that all data has been sent; if only some of the data was transmitted, the application needs to attempt delivery of the remaining data." (Source)

We avoided having to do this by using sendall():

"Unlike send(), this method continues to send data from bytes until either all data has been sent or an error occurs. None is returned on success." (Source)

We have two problems at this point:

How do we handle multiple connections concurrently?

We need to call send() and recv() until all data is sent or received.

What do we do? There are many approaches to concurrency. More recently, a popular approach is to use Asynchronous I/O. asyncio was introduced into the standard library in Python 3.4. The traditional choice is to use threads.

The trouble with concurrency is it's hard to get right. There are many subtleties to consider and guard against. All it takes is for one of these to manifest itself and your application may suddenly fail in not-so-subtle ways.

I don't say this to scare you away from learning and using concurrent programming. If your application needs to scale, it's a necessity if you want to use more than one processor or one core. However, for this tutorial, we'll use something that's more traditional than threads and easier to reason about. We're going to use the granddaddy of system calls: .

"This module allows high-level and efficient I/O multiplexing, built upon the select module primitives. Users are encouraged to use this module instead, unless they want precise control over the OS-level primitives used." (Source)

Even though, by using select(), we're not able to run concurrently, depending on your workload, this approach may still be plenty fast. It depends on what your application needs to do when it services a request and the number of clients it needs to support.

uses single-threaded cooperative multitasking and an event loop to manage tasks. With select(), we'll be writing our own version of an event loop, albeit more simply and synchronously. When using multiple threads, even though you have concurrency, we currently have to use the GIL with CPython and PyPy. This effectively limits the amount of work we can do in parallel anyway.

I say all of this to explain that using select() may be a perfectly fine choice. Don't feel like you have to use asyncio, threads, or the latest asynchronous library. Typically, in a network application, your application is I/O bound: it could be waiting on the local network, endpoints on the other side of the network, on a disk, and so forth.

If you're getting requests from clients that initiate CPU bound work, look at the concurrent.futures module. It contains the class ProcessPoolExecutor that uses a pool of processes to execute calls asynchronously.

If you use multiple processes, the operating system is able to schedule your Python code to run in parallel on multiple processors or cores, without the GIL. For ideas and inspiration, see the PyCon talk John Reese - Thinking Outside the GIL with AsyncIO and Multiprocessing - PyCon 2018.

Multi-Connection Client and Server

In the next two sections, we'll create a server and client that handles multiple connections using a selector object created from the selectors module.

Multi-Connection Server

First, let's look at the multi-connection server, multiconn-server.py. Here's the first part that sets up the listening socket:

The biggest difference between this server and the echo server is the call to lsock.setblocking(False) to configure the socket in non-blocking mode. Calls made to this socket will no longer block. When it's used with sel.select(), as you'll see below, we can wait for events on one or more sockets and then read and write data when it's ready.

Next is the event loop:

sel.select(timeout=None) blocks until there are sockets ready for I/O. It returns a list of (key, events) tuples, one for each socket. key is a SelectorKey namedtuple that contains a fileobj attribute. key.fileobj is the socket object, and mask is an event mask of the operations that are ready.

Let's look at what our accept_wrapper() function does:

Remember, this is the main objective in this version of the server since we don't want it to block. If it blocks, then the entire server is stalled until it returns. Which means other sockets are left waiting. This is the dreaded "hang" state that you don't want your server to be in.

Next, we create an object to hold the data we want included along with the socket using the class types.SimpleNamespace. Since we want to know when the client connection is ready for reading and writing, both of those events are set using the following:

The events mask, socket, and data objects are then passed to sel.register().

Now let's look at service_connection() to see how a client connection is handled when it's ready:

Note the else: block if no data is received:

This means that the client has closed their socket, so the server should too. But don't forget to first call sel.unregister() so it's no longer monitored by select().

When the socket is ready for writing, which should always be the case for a healthy socket, any received data stored in data.outb is echoed to the client using sock.send(). The bytes sent are then removed from the send buffer:

Multi-Connection Client

Now let's look at the multi-connection client, multiconn-client.py. It's very similar to the server, but instead of listening for connections, it starts by initiating connections via start_connections():

num_conns is read from the command-line, which is the number of connections to create to the server. Just like the server, each socket is set to non-blocking mode.

connect_ex() is used instead of connect() since connect() would immediately raise a BlockingIOError exception. connect_ex() initially returns an error indicator, errno.EINPROGRESS, instead of raising an exception while the connection is in progress. Once the connection is completed, the socket is ready for reading and writing and is returned as such by select().

Let's look at service_connection(). It's fundamentally the same as the server:

There's one important difference. It keeps track of the number of bytes it's received from the server so it can close its side of the connection. When the server detects this, it closes its side of the connection too.

Note that by doing this, the server depends on the client being well-behaved: the server expects the client to close its side of the connection when it's done sending messages. If the client doesn't close, the server will leave the connection open. In a real application, you may want to guard against this in your server and prevent client connections from accumulating if they don't send a request after a certain amount of time.

Running the Multi-Connection Client and Server

Now let's run multiconn-server.py and multiconn-client.py. They both use command-line arguments. You can run them without arguments to see the options.

For the server, pass a host and port number:

For the client, also pass the number of connections to create to the server, num_connections:

Below is the server output when listening on the loopback interface on port 65432:

$ ./multiconn-server.py 127.0.0.1 65432
listening on ('127.0.0.1', 65432)
accepted connection from ('127.0.0.1', 61354)
accepted connection from ('127.0.0.1', 61355)
echoing b'Message 1 from client.Message 2 from client.' to ('127.0.0.1', 61354)
echoing b'Message 1 from client.Message 2 from client.' to ('127.0.0.1', 61355)
closing connection to ('127.0.0.1', 61354)
closing connection to ('127.0.0.1', 61355)

Below is the client output when it creates two connections to the server above:

Application Client and Server

The multi-connection client and server example is definitely an improvement compared with where we started. However, let's take one more step and address the shortcomings of the previous "multiconn" example in a final implementation: the application client and server.

We want a client and server that handles errors appropriately so other connections aren't affected. Obviously, our client or server shouldn't come crashing down in a ball of fury if an exception isn't caught. This is something we haven't discussed up until now. I've intentionally left out error handling for brevity and clarity in the examples.

Now that you're familiar with the basic API, non-blocking sockets, and select(), we can add some error handling and discuss the "elephant in the room" that I've kept hidden from you behind that large curtain over there. Yes, I'm talking about the custom class I mentioned way back in the introduction. I knew you wouldn't forget.

First, let's address the errors:

"All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised; starting from Python 3.3, errors related to socket or address semantics raise OSError or one of its subclasses." (Source)

We need to catch OSError. Another thing I haven't mentioned in relation to errors is timeouts. You'll see them discussed in many places in the documentation. Timeouts happen and are a "normal" error. Hosts and routers are rebooted, switch ports go bad, cables go bad, cables get unplugged, you name it. You should be prepared for these and other errors and handle them in your code.

What about the "elephant in the room?" As hinted by the socket type socket.SOCK_STREAM, when using TCP, you're reading from a continuous stream of bytes. It's like reading from a file on disk, but instead you're reading bytes from the network.

However, unlike reading a file, there's no . In other words, you can't reposition the socket pointer, if there was one, and move randomly around the data reading whatever, whenever you'd like.

When bytes arrive at your socket, there are network buffers involved. Once you've read them, they need to be saved somewhere. Calling recv() again reads the next stream of bytes available from the socket.

What this means is that you'll be reading from the socket in chunks. You need to call recv() and save the data in a buffer until you've read enough bytes to have a complete message that makes sense to your application.

It's up to you to define and keep track of where the message boundaries are. As far as the TCP socket is concerned, it's just sending and receiving raw bytes to and from the network. It knows nothing about what those raw bytes mean.

This bring us to defining an application-layer protocol. What's an application-layer protocol? Put simply, your application will send and receive messages. These messages are your application's protocol.

In other words, the length and format you choose for these messages define the semantics and behavior of your application. This is directly related to what I explained in the previous paragraph regarding reading bytes from the socket. When you're reading bytes with recv(), you need to keep up with how many bytes were read and figure out where the message boundaries are.

How is this done? One way is to always send fixed-length messages. If they're always the same size, then it's easy. When you've read that number of bytes into a buffer, then you know you have one complete message.

However, using fixed-length messages is inefficient for small messages where you'd need to use padding to fill them out. Also, you're still left with the problem of what to do about data that doesn't fit into one message.

In this tutorial, we'll take a generic approach. An approach that's used by many protocols, including HTTP. We'll prefix messages with a header that includes the content length as well as any other fields we need. By doing this, we'll only need to keep up with the header. Once we've read the header, we can process it to determine the length of the message's content and then read that number of bytes to consume it.

We'll implement this by creating a custom class that can send and receive messages that contain text or binary data. You can improve and extend it for your own applications. The most important thing is that you'll be able to see an example of how this is done.

I need to mention something regarding sockets and bytes that may affect you. As we talked about earlier, when sending and receiving data via sockets, you're sending and receiving raw bytes.

If you receive data and want to use it in a context where it's interpreted as multiple bytes, for example a 4-byte integer, you'll need to take into account that it could be in a format that's not native to your machine's CPU. The client or server on the other end could have a CPU that uses a different byte order than your own. If this is the case, you'll need to convert it to your host's native byte order before using it.

This byte order is referred to as a CPU's endianness. See Byte Endianness in the reference section for details. We'll avoid this issue by taking advantage of Unicode for our message header and using the encoding UTF-8. Since UTF-8 uses an 8-bit encoding, there are no byte ordering issues.

You can find an explanation in Python's Encodings and Unicode documentation. Note that this applies to the text header only. We'll use an explicit type and encoding defined in the header for the content that's being sent, the message payload. This will allow us to transfer any data we'd like (text or binary), in any format.

You can easily determine the byte order of your machine by using sys.byteorder. For example, on my Intel laptop, this happens:

If I run this in a virtual machine that emulates a big-endian CPU (PowerPC), then this happens:

In this example application, our application-layer protocol defines the header as Unicode text with a UTF-8 encoding. For the actual content in the message, the message payload, you'll still have to swap the byte order manually if needed.

This will depend on your application and whether or not it needs to process multi-byte binary data from a machine with a different endianness. You can help your client or server implement binary support by adding additional headers and using them to pass parameters, similar to HTTP.

Don't worry if this doesn't make sense yet. In the next section, you'll see how all of this works and fits together.

Let's fully define the protocol header. The protocol header is:

Variable-length text

Unicode with the encoding UTF-8

A Python dictionary serialized using JSON

The required headers, or sub-headers, in the protocol header's dictionary are as follows:

The byte order of the machine (uses sys.byteorder). This may not be required for your application.

content-length
The length of the content in bytes.

content-type
The type of content in the payload, for example, text/json or binary/my-binary-type.

content-encoding
The encoding used by the content, for example, utf-8 for Unicode text or binary for binary data.

These headers inform the receiver about the content in the payload of the message. This allows you to send arbitrary data while providing enough information so the content can be decoded and interpreted correctly by the receiver. Since the headers are in a dictionary, it's easy to add additional headers by inserting key/value pairs as needed.

Sending an Application Message

There's still a bit of a problem. We have a variable-length header, which is nice and flexible, but how do you know the length of the header when reading it with recv()?

When we previously talked about using recv() and message boundaries, I mentioned that fixed-length headers can be inefficient. That's true, but we're going to use a small, 2-byte, fixed-length header to prefix the JSON header that contains its length.

You can think of this as a hybrid approach to sending messages. In effect, we're bootstrapping the message receive process by sending the length of the header first. This makes it easy for our receiver to deconstruct the message.

To give you a better idea of the message format, let's look at a message in its entirety:

A message starts with a fixed-length header of 2 bytes that's an integer in network byte order. This is the length of the next header, the variable-length JSON header. Once we've read 2 bytes with recv(), then we know we can process the 2 bytes as an integer and then read that number of bytes before decoding the UTF-8 JSON header.

The JSON header contains a dictionary of additional headers. One of those is content-length, which is the number of bytes of the message's content (not including the JSON header). Once we've called recv() and read content-length bytes, we've reached a message boundary and read an entire message.

Application Message Class

Finally, the payoff! Let's look at the Message class and see how it's used with select() when read and write events happen on the socket.

For this example application, I had to come up with an idea for what types of messages the client and server would use. We're far beyond toy echo clients and servers at this point.

To keep things simple and still demonstrate how things would work in a real application, I created an application protocol that implements a basic search feature. The client sends a search request and the server does a lookup for a match. If the request sent by the client isn't recognized as a search, the server assumes it's a binary request and returns a binary response.

After reading the following sections, running the examples, and experimenting with the code, you'll see how things work. You can then use the Message class as a starting point and modify it for your own use.

As we discussed before and you'll see below, working with sockets involves keeping state. By using a class, we keep all of the state, data, and code bundled together in an organized unit. An instance of the class is created for each socket in the client and server when a connection is started or accepted.

The class is mostly the same for both the client and the server for the wrapper and utility methods. They start with an underscore, like Message._json_encode(). These methods simplify working with the class. They help other methods by allowing them to stay shorter and support the DRY principle.

The server's Message class works in essentially the same way as the client's and vice-versa. The difference being that the client initiates the connection and sends a request message, followed by processing the server's response message. Conversely, the server waits for a connection, processes the client's request message, and then sends a response message.

It looks like this:

Here's the file and code layout:

Message Entry Point

I'd like to discuss how the Message class works by first mentioning an aspect of its design that wasn't immediately obvious to me. Only after refactoring it at least five times did I arrive at what it is currently. Why? Managing state.

After a Message object is created, it's associated with a socket that's monitored for events using selector.register():

Note: Some of the code examples in this section are from the server's main script and Message class, but this section and discussion applies equally to the client as well. I'll show and explain the client's version when it differs.

Let's see what the process_events() method does:

This brings us back to managing state. After a few refactorings, I decided that if another method depended on state variables having a certain value, then they would only be called from read() and write(). This keeps the logic as simple as possible as events come in on the socket for processing.

This may seem obvious, but the first few iterations of the class were a mix of some methods that checked the current state and, depending on their value, called other methods to process data outside read() or write(). In the end, this proved too complex to manage and keep up with.

You should definitely modify the class to suit your own needs so it works best for you, but I'd recommend that you keep the state checks and the calls to methods that depend on that state to the read() and write() methods if possible.

The _read() method is called first. It calls socket.recv() to read data from the socket and store it in a receive buffer.

Remember that when socket.recv() is called, all of the data that makes up a complete message may not have arrived yet. socket.recv() may need to be called again. This is why there are state checks for each part of the message before calling the appropriate method to process it.

Before a method processes its part of the message, it first checks to make sure enough bytes have been read into the receive buffer. If there are, it processes its respective bytes, removes them from the buffer and writes its output to a variable that's used by the next processing stage. Since there are three components to a message, there are three state checks and process method calls:

Next, let's look at write(). This is the server's version:

The _write() method calls socket.send() if there's data in the send buffer.

The client version of write() is similar:

Just like the server, _write() calls socket.send() if there's data in the send buffer.

The notable difference in the client's version of write() is the last check to see if the request has been queued. This will be explained more in the section Client Main Script, but the reason for this is to tell selector.select() to stop monitoring the socket for write events. If the request has been queued and the send buffer is empty, then we're done writing and we're only interested in read events. There's no reason to be notified that the socket is writable.

This is important because process_events() will be called many times over the life of the connection. Therefore, make sure that any methods that should only be called once are either checking a state variable themselves, or the state variable set by the method is checked by the caller.

Server Main Script

In the server's main script app-server.py, arguments are read from the command line that specify the interface and port to listen on:

For example, to listen on the loopback interface on port 65432, enter:

Use an empty string for <host> to listen on all interfaces.

After creating the socket, a call is made to socket.setsockopt() with the option socket.SO_REUSEADDR:

Setting this socket option avoids the error Address already in use. You'll see this when starting the server and a previously used TCP socket on the same port has connections in the TIME_WAIT state.

The event loop catches any errors so the server can stay up and continue to run:

When a client connection is accepted, a Message object is created:

The Message object is associated with the socket in the call to sel.register() and is initially set to be monitored for read events only. Once the request has been read, we'll modify it to listen for write events only.

An advantage of taking this approach in the server is that in most cases, when a socket is healthy and there are no network issues, it will always be writable.

Server Message Class

In the section Message Entry Point, we looked at how the Message object was called into action when socket events were ready via process_events(). Now let's look at what happens as data is read on the socket and a component, or piece, of the message is ready to be processed by the server.

The server's message class is in libserver.py. You can find the source code on GitHub.

The methods appear in the class in the order in which processing takes place for a message.

When the server has read at least 2 bytes, the fixed-length header can be processed:

The fixed-length header is a 2-byte integer in network (big-endian) byte order that contains the length of the JSON header. struct.unpack() is used to read the value, decode it, and store it in self._jsonheader_len. After processing the piece of the message it's responsible for, process_protoheader() removes it from the receive buffer.

Just like the fixed-length header, when there's enough data in the receive buffer to contain the JSON header, it can be processed as well:

Next is the actual content, or payload, of the message. It's described by the JSON header in self.jsonheader. When content-length bytes are available in the receive buffer, the request can be processed:

After saving the message content to the data variable, process_request() removes it from the receive buffer. Then, if the content type is JSON, it decodes and deserializes it. If it's not, for this example application, it assumes it's a binary request and simply prints the content type.

The last thing process_request() does is modify the selector to monitor write events only. In the server's main script, app-server.py, the socket is initially set to monitor read events only. Now that the request has been fully processed, we're no longer interested in reading.

A response can now be created and written to the socket. When the socket is writable, create_response() is called from write():

A response is created by calling other methods, depending on the content type. In this example application, a simple dictionary lookup is done for JSON requests when action == 'search'. You can define other methods for your own applications that get called here.

One tricky bit to figure out was how to close the connection after the response is written. I put the call to close() in the method _write():

Although it's somewhat "hidden," I think it's an acceptable trade-off given that the Message class only handles one message per connection. After the response is written, there's nothing left for the server to do. It's completed its work.

Client Main Script

In the client's main script app-client.py, arguments are read from the command line and used to create requests and start connections to the server:

Here's an example:

After creating a dictionary representing the request from the command-line arguments, the host, port, and request dictionary are passed to start_connection():

A socket is created for the server connection as well as a Message object using the request dictionary.

Like the server, the Message object is associated with the socket in the call to sel.register(). However, for the client, the socket is initially set to be monitored for both read and write events. Once the request has been written, we'll modify it to listen for read events only.

This approach gives us the same advantage as the server: not wasting CPU cycles. After the request has been sent, we're no longer interested in write events, so there's no reason to wake up and process them.

Client Message Class

In the section Message Entry Point, we looked at how the message object was called into action when socket events were ready via process_events(). Now let's look at what happens after data is read and written on the socket and a message is ready to be processed by the client.

The client's message class is in libclient.py. You can find the source code on GitHub.

The methods appear in the class in the order in which processing takes place for a message.

The first task for the client is to queue the request:

The dictionaries used to create the request, depending on what was passed on the command line, are in the client's main script, app-client.py. The request dictionary is passed as an argument to the class when a Message object is created.

After the request has been sent, the client waits for a response from the server.

Last, but certainly not least, is the final call for process_response():

Message Class Wrapup

I'll conclude the Message class discussion by mentioning a couple of things that are important to notice with a few of the supporting methods.

Any exceptions raised by the class are caught by the main script in its except clause:

Note the last line: message.close().

The methods Message._read() and Message._write() also contain something interesting:

Note the except line: except BlockingIOError:.

By catching and skipping over the exception with pass, select() will eventually call us again, and we'll get another chance to read or write the data.

Running the Application Client and Server

After all of this hard work, let's have some fun and run some searches!

In these examples, I'll run the server so it listens on all interfaces by passing an empty string for the host argument. This will allow me to run the client and connect from a virtual machine that's on another network. It emulates a big-endian PowerPC machine.

First, let's start the server:

Now let's run the client and enter a search. Let's see if we can find him:

My terminal is running a shell that's using a text encoding of Unicode (UTF-8), so the output above prints nicely with emojis.

Let's see if we can find the puppies:

This demonstrates that we're sending raw bytes over the network and they need to be decoded by the receiver to be interpreted correctly. This is why we went to all of the trouble to create a header that contains the content type and encoding.

Here's the server output from both client connections above:

Look at the sending line to see the bytes that were written to the client's socket. This is the server's response message.

You can also test sending binary requests to the server if the action argument is anything other than search:

Troubleshooting

Inevitably, something won't work, and you'll be wondering what to do. Don't worry, it happens to all of us. Hopefully, with the help of this tutorial, your debugger, and favorite search engine, you'll be able to get going again with the source code part.

If not, your first stop should be Python's socket module documentation. Make sure you read all of the documentation for each function or method you're calling. Also, read through the Reference section for ideas. In particular, check the Errors section.

Sometimes, it's not all about the source code. The source code might be correct, and it's just the other host, the client or server. Or it could be the network, for example, a router, firewall, or some other networking device that's playing man-in-the-middle.

For these types of issues, additional tools are essential. Below are a few tools and utilities that might help or at least provide some clues.

ping

ping will check if a host is alive and connected to the network by sending an ICMP echo request. It communicates directly with the operating system's TCP/IP protocol stack, so it works independently from any application running on the host.

Below is an example of running ping on macOS:

$ ping -c 3 127.0.0.1
PING 127.0.0.1 (127.0.0.1): 56 data bytes
64 bytes from 127.0.0.1: icmp_seq=0 ttl=64 time=0.058 ms
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.165 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.164 ms

--- 127.0.0.1 ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.058/0.129/0.165/0.050 ms

Note the statistics at the end of the output. This can be helpful when you're trying to discover intermittent connectivity problems. For example, is there any packet loss? How much latency is there (see the round-trip times)?

If there's a firewall between you and the other host, a ping's echo request may not be allowed. Some firewall administrators implement policies that enforce this. The idea being that they don't want their hosts to be discoverable. If this is the case and you have firewall rules added to allow the hosts to communicate, make sure that the rules also allow ICMP to pass between them.

ICMP is the protocol used by ping, but it's also the protocol TCP and other lower-level protocols use to communicate error messages. If you're experiencing strange behavior or slow connections, this could be the reason.

ICMP messages are identified by type and code. To give you an idea of the important information they carry, here are a few:

See the article Path MTU Discovery for information regarding fragmentation and ICMP messages. This is an example of something that can cause strange behavior that I mentioned previously.

netstat

In the section Viewing Socket State, we looked at how netstat can be used to display information about sockets and their current state. This utility is available on macOS, Linux, and Windows.

I didn't mention the columns Recv-Q and Send-Q in the example output. These columns will show you the number of bytes that are held in network buffers that are queued for transmission or receipt, but for some reason haven't been read or written by the remote or local application.

In other words, the bytes are waiting in network buffers in the operating system's queues. One reason could be the application is CPU bound or is otherwise unable to call socket.recv() or socket.send() and process the bytes. Or there could be network issues affecting communications like congestion or failing network hardware or cabling.

To demonstrate this and see how much data I could send before seeing an error, I wrote a test client that connects to a test server and repeatedly calls socket.send(). The test server never calls socket.recv(). It just accepts the connection. This causes the network buffers on the server to fill, which eventually raises an error on the client.

First, I started the server:

Then I ran the client. Let's see what the error is:

$ ./app-client-test.py 127.0.0.1 65432 binary test
error: socket.send() blocking io exception for ('127.0.0.1', 65432):
BlockingIOError(35, 'Resource temporarily unavailable')

Here's the netstat output while the client and server were still running, with the client printing out the error message above multiple times:

$ netstat -an | grep 65432
Proto Recv-Q Send-Q  Local Address          Foreign Address        (state)
tcp4  408300      0  127.0.0.1.65432        127.0.0.1.53225        ESTABLISHED
tcp4       0 269868  127.0.0.1.53225        127.0.0.1.65432        ESTABLISHED
tcp4       0      0  127.0.0.1.65432        *.*                    LISTEN

The first entry is the server ( Local Address has port 65432):

Notice the Recv-Q: 408300.

The second entry is the client ( Foreign Address has port 65432):

Notice the Send-Q: 269868.

The client sure was trying to write bytes, but the server wasn't reading them. This caused the server's network buffer queue to fill on the receive side and the client's network buffer queue to fill on the send side.

Windows

If you work with Windows, there's a suite of utilities that you should definitely check out if you haven't already: Windows Sysinternals.

Wireshark

Sometimes you need to see what's happening on the wire. Forget about what the application log says or what the value is that's being returned from a library call. You want to see what's actually being sent or received on the network. Just like debuggers, when you need to see it, there's no substitute.

Wireshark is a network protocol analyzer and traffic capture application that runs on macOS, Linux, and Windows, among others. There's a GUI version named wireshark, and also a terminal, text-based version named tshark.

Running a traffic capture is a great way to watch how an application behaves on the network and gather evidence about what it sends and receives, and how often and how much. You'll also be able to see when a client or server closes or aborts a connection or stops responding. This information can be extremely helpful when you're troubleshooting.

There are many good tutorials and other resources on the web that will walk you through the basics of using Wireshark and TShark.

Here's an example of a traffic capture using Wireshark on the loopback interface:

Here's the same example shown above using tshark:

Reference

This section serves as a general reference with additional information and links to external resources.

Python Documentation

Errors

The following is from Python's socket module documentation:

"All errors raise exceptions. The normal exceptions for invalid argument types and out-of-memory conditions can be raised; starting from Python 3.3, errors related to socket or address semantics raise OSError or one of its subclasses." (Source)

Here are some common errors you'll probably encounter when working with sockets:

OSError

EADDRINUSE

Address already in use. Make sure there's not another process running that's using the same port number and your server is setting the socket option SO_REUSEADDR: socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1).

Socket Address Families

socket.AF_INET
IPv4

host is a string with a hostname like 'www.example.com' or an IPv4 address like '10.1.2.3'. port is an integer.

socket.AF_INET6
IPv6
(host, port, flowinfo, scopeid)
host is a string with a hostname like 'www.example.com' or an IPv6 address like 'fe80::6203:7ab:fe88:9c23'. port is an integer. flowinfo and scopeid represent the sin6_flowinfo and sin6_scope_id members in the C struct sockaddr_in6.

Note the excerpt below from Python's socket module documentation regarding the host value of the address tuple:

"For IPv4 addresses, two special forms are accepted instead of a host address: the empty string represents INADDR_ANY, and the string '<broadcast>' represents INADDR_BROADCAST. This behavior is not compatible with IPv6, therefore, you may want to avoid these if you intend to support IPv6 with your Python programs." (Source)

See Python's Socket families documentation for more information.

I've used IPv4 sockets in this tutorial, but if your network supports it, try testing and using IPv6 if possible. One way to support this easily is by using the function socket.getaddrinfo(). It translates the host and port arguments into a sequence of 5-tuples that contains all of the necessary arguments for creating a socket connected to that service. socket.getaddrinfo() will understand and interpret passed-in IPv6 addresses and hostnames that resolve to IPv6 addresses, in addition to IPv4.

The following example returns address information for a TCP connection to example.org on port 80:

Using Hostnames

The following is from Python's socket module documentation:

"If you use a hostname in the host portion of IPv4/v6 socket address, the program may show a non-deterministic behavior, as Python uses the first address returned from the DNS resolution. The socket address will be resolved differently into an actual IPv4/v6 address, depending on the results from DNS resolution and/or the host configuration. For deterministic behavior use a numeric address in host portion." (Source)

The standard convention for the name " localhost" is for it to resolve to 127.0.0.1 or ::1, the loopback interface. This will more than likely be the case for you on your system, but maybe not. It depends on how your system is configured for name resolution. As with all things IT, there are always exceptions, and there are no guarantees that using the name "localhost" will connect to the loopback interface.

For example, on Linux, see man nsswitch.conf, the Name Service Switch configuration file. Another place to check on macOS and Linux is the file /etc/hosts. On Windows, see C:\Windows\System32\drivers\etc\hosts. The hosts file contains a static table of name to address mappings in a simple text format. DNS is another piece of the puzzle altogether.

Interestingly enough, as of this writing (June 2018), there's an RFC draft Let 'localhost' be localhost that discusses the conventions, assumptions and security around using the name "localhost."

What's important to understand is that when you use hostnames in your application, the returned address(es) could literally be anything. Don't make assumptions regarding a name if you have a security-sensitive application. Depending on your application and environment, this may or may not be a concern for you.

Note: Security precautions and best practices still apply, even if your application isn't "security-sensitive." If your application accesses the network, it should be secured and maintained. This means, at a minimum:

System software updates and security patches are applied regularly, including Python. Are you using any third party libraries? If so, make sure those are checked and updated too.

If possible, use a dedicated or host-based firewall to restrict connections to trusted systems only.

What DNS servers are configured? Do you trust them and their administrators?

Make sure that request data is sanitized and validated as much as possible prior to calling other code that processes it. Use (fuzz) tests for this and run them regularly.

Regardless of whether or not you're using hostnames, if your application needs to support secure connections (encryption and authentication), you'll probably want to look into using TLS. This is its own separate topic and beyond the scope of this tutorial. See Python's ssl module documentation to get started. This is the same protocol that your web browser uses to connect securely to web sites.

With interfaces, IP addresses, and name resolution to consider, there are many variables. What should you do? Here are some recommendations that you can use if you don't have a network application review process:

For clients or servers, if you need to authenticate the host you're connecting to, look into using TLS.

Blocking Calls

Blocking socket calls can be set to non-blocking mode so they return immediately. If you do this, you'll need to at least refactor or redesign your application to handle the socket operation when it's ready.

By default, sockets are always created in blocking mode. See Notes on socket timeouts for a description of the three modes.

Closing Connections

An interesting thing to note with TCP is it's completely legal for the client or server to close their side of the connection while the other side remains open. This is referred to as a "half-open" connection. It's the application's decision whether or not this is desirable. In general, it's not. In this state, the side that's closed their end of the connection can no longer send data. They can only receive it.

I'm not advocating that you take this approach, but as an example, HTTP uses a header named "Connection" that's used to standardize how applications should close or persist open connections. For details, see section 6.3 in RFC 7230, Hypertext Transfer Protocol (HTTP/1.1): Message Syntax and Routing.

When designing and writing your application and its application-layer protocol, it's a good idea to go ahead and work out how you expect connections to be closed. Sometimes this is obvious and simple, or it's something that can take some initial prototyping and testing. It depends on the application and how the message loop is processed with its expected data. Just make sure that sockets are always closed in a timely manner after they complete their work.

Byte Endianness

See Wikipedia's article on endianness for details on how different CPUs store byte orderings in memory. When interpreting individual bytes, this isn't a problem. However, when handling multiple bytes that are read and processed as a single value, for example a 4-byte integer, the byte order needs to be reversed if you're communicating with a machine that uses a different endianness.

Byte order is also important for text strings that are represented as multi-byte sequences, like Unicode. Unless you're always using "true," strict ASCII and control the client and server implementations, you're probably better off using Unicode with an encoding like UTF-8 or one that supports a byte order mark (BOM).

It's important to explicitly define the encoding used in your application-layer protocol. You can do this by mandating that all text is UTF-8 or using a "content-encoding" header that specifies the encoding. This prevents your application from having to detect the encoding, which you should avoid if possible.

This becomes problematic when there is data involved that's stored in files or a database and there's no metadata available that specifies its encoding. When the data is transferred to another endpoint, it will have to try to detect the encoding. For a discussion, see Wikipedia's Unicode article that references RFC 3629: UTF-8, a transformation format of ISO 10646:

"However RFC 3629, the UTF-8 standard, recommends that byte order marks be forbidden in protocols using UTF-8, but discusses the cases where this may not be possible. In addition, the large restriction on possible patterns in UTF-8 (for instance there cannot be any lone bytes with the high bit set) means that it should be possible to distinguish UTF-8 from other character encodings without relying on the BOM." (Source)

The takeaway from this is to always store the encoding used for data that's handled by your application if it can vary. In other words, try to somehow store the encoding as metadata if it's not always UTF-8 or some other encoding with a BOM. Then you can send that encoding in a header along with the data to tell the receiver what it is.

The byte ordering used in TCP/IP is big-endian and is referred to as network order. Network order is used to represent integers in lower layers of the protocol stack, like IP addresses and port numbers. Python's socket module includes functions that convert integers to and from network and host byte order:

socket.ntohl(x)
Convert 32-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation.

socket.ntohs(x)
Convert 16-bit positive integers from network to host byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.

socket.htonl(x)
Convert 32-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 4-byte swap operation.

socket.htons(x)
Convert 16-bit positive integers from host to network byte order. On machines where the host byte order is the same as network byte order, this is a no-op; otherwise, it performs a 2-byte swap operation.

You can also use the struct module to pack and unpack binary data using format strings:

Conclusion

We covered a lot of ground in this tutorial. Networking and sockets are large subjects. If you're new to networking or sockets, don't be discouraged by all of the terms and acronyms.

There are a lot of pieces to become familiar with in order to understand how everything works together. However, just like Python, it will start to make more sense as you get to know the individual pieces and spend more time with them.

We looked at the low-level socket API in Python's socket module and saw how it can be used to create client-server applications. We also created our own custom class and used it as an application-layer protocol to exchange messages and data between endpoints. You can use this class and build upon it to learn and help make creating your own socket applications easier and faster.

You can find the source code on GitHub.

Congratulations on making it to the end! You are now well on your way to using sockets in your own applications.

I hope this tutorial has given you the information, examples, and inspiration needed to start you on your sockets development journey.

# data[].attributes.attachment_link.title
Socket Programming in Python (Guide) - Real Python

# data[].attributes.attachment_link.description
In this in-depth tutorial you'll learn how to build a socket server and client with Python. By the end of this tutorial, you'll understand how to use the main functions and methods in Python's socket module to write your own networked client-server applications.

# data[].attributes.attachment_link.readable_text
Sockets (aka socket programming) enable programs to send and receive data, bi-directionally, at any given moment. This tutorial walks through how you can send data from device-to-device, client-to-server, and vice versa using socket programming in Python.

Why use sockets to send data?

Internet-connected applications that need to operate in realtime greatly benefit from the implementation of sockets in their networking code. Some examples of apps that use socket programming are:

Python, unlike JavaScript, is a language that executes synchronously. This is why asyncio was developed - to make Python more robust, particularly for the nature of socket programming.

With streaming sockets, data can be sent or received at any time. In case your Python program is in the middle of executing some code, other threads can handle the new socket data. Libraries like asyncio implement multiple threads, so your Python program can work in an asynchronous fashion.

Python Socket Programming Tutorial

Natively, Python provides a socket class so developers can easily implement socket objects in their source code. To use a socket object in your program, start off by importing the socket library. No need to install it with a package manager, it comes out of the box with Python.

import socket

Now we can create socket objects in our code.

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

This code creates a socket object that we are storing in the "sock" variable. The constructor is provided a family and type parameter respectively. The family parameter is set to the default value, which is the Address Format Internet.

The type parameter is set to Socket Stream, also the default which enables "sequenced, reliable, two-way, connection-based byte streams" over TCP.

Once we have an initialized socket object, we can use some methods to open a connection, send data, receive data, and finally close the connection.

## Connect to an IP with Port, could be a URL
sock.connect(('0.0.0.0', 8080))

## Send some data, this method can be called multiple times
sock.send("Twenty-five bytes to send")

## Receive up to 4096 bytes from a peer
sock.recv(4096)

## Close the socket connection, no more data transmission
sock.close()

Python Socket Server

Now that we know a few methods for transmitting bytes, let's create a client and server program with Python.

import socket

serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

serv.bind(('0.0.0.0', 8080))
serv.listen(5)

while True:
    conn, addr = serv.accept()
    from_client = ''

    while True:
        data = conn.recv(4096)
        if not data: break
        from_client += data
        print from_client

        conn.send("I am SERVER\n")

    conn.close()
    print 'client disconnected'

This code makes a socket object, and binds it to localhost's port 8080 as a socket server. When clients connect to this address with a socket connection, the server listens for data, and stores it in the "data" variable.

Next, the program logs the client data using "print," and then sends a string to the client: I am SERVER.

Let's take a look at client code that would interact with this server program.

Python Socket Client

Here is the client socket demo code.

import socket

client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('0.0.0.0', 8080))

client.send("I am CLIENT\n")

from_server = client.recv(4096)

client.close()

print from_server

This client opens up a socket connection with the server, but only if the server program is currently running. To test this out yourself, you will need to use 2 terminal windows at the same time.

Next, the client sends some data to the server: I am CLIENT

Then the client receives some data it anticipates from the server.

Done! You can now get started streaming data between clients and servers using some basic Python network programming.

How Do You Send Data Between Clients?

Sending data between 2 or more client devices over the internet is tricky. Due to protections implemented by network security, not all devices connected to the world wide web have a publicly accessible internet protocol (IP) address.

This means that the Python code that we implemented will not be 100% reliable for sending peer-to-peer data in our realtime app. How do we achieve reliability and speed when transmitting peer-to-peer data?

This can be accomplished using a server in the middle. Client devices using the internet can connect to a server with a public IP address (or a website domain). Then, this broker in the middle can pass messages routed to 1 or many clients.

PubNub does this best with the Pub/Sub API. It is fast, reliable, secure, and easy to implement on any client device. Whether you have a Python server, a JavaScript website, or anything in between, you can use PubNub to send data to anyone in under 250ms.

With One-to-Many, One-to-One, or Many-to-Many, PubNub scales automatically to support any application load. Using the API opens up an instant, always-on connection between all clients that have the Pub/Sub API keys. This accomplishes the same objectives as a socket connection.

PubNub and Python with an SSL Connection

Here is an example of peer-to-peer data that is sent with PubNub, on a single channel, with SSL. You can think of this like sending data over a TCP socket. When you sign up for a free PubNub account, you can use a practically infinite number of channels to send messages in realtime. Before you try the code, be sure to make a free PubNub account.

Client 1

from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
import time
import os

pnconfig = PNConfiguration()

pnconfig.publish_key = 'your pubnub publish key here'
pnconfig.subscribe_key = 'your pubnub subscribe key here'
pnconfig.ssl = True

pubnub = PubNub(pnconfig)

def my_publish_callback(envelope, status):
    # Check whether request successfully completed or not
    if not status.is_error():
        pass

class MySubscribeCallback(SubscribeCallback):
    def presence(self, pubnub, presence):
        pass
    def status(self, pubnub, status):
        pass
    def message(self, pubnub, message):
        print "from device 2: " + message.message

pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels("chan-1").execute()

## publish a message
while True:
    msg = raw_input("Input a message to publish: ")
    if msg == 'exit': os._exit(1)
    pubnub.publish().channel("chan-1").message(str(msg)).pn_async(my_publish_callback)

Client 2

Strings can be entered on the command line for these 2 client programs. Maximum message size for PubNub publishing is 32kb. Use 2 terminal windows to try out the code!

from pubnub.callbacks import SubscribeCallback
from pubnub.enums import PNStatusCategory
from pubnub.pnconfiguration import PNConfiguration
from pubnub.pubnub import PubNub
import time
import os

pnconfig = PNConfiguration()

pnconfig.publish_key = 'your pubnub publish key here'
pnconfig.subscribe_key = 'your pubnub subscribe key here'
pnconfig.ssl = True

pubnub = PubNub(pnconfig)

def my_publish_callback(envelope, status):
    # Check whether request successfully completed or not
    if not status.is_error():
        pass

class MySubscribeCallback(SubscribeCallback):
    def presence(self, pubnub, presence):
        pass
    def status(self, pubnub, status):
        pass
    def message(self, pubnub, message):
        print "from device 1: " + message.message

pubnub.add_listener(MySubscribeCallback())
pubnub.subscribe().channels("chan-1").execute()

## publish a message
while True:
    msg = raw_input("Input a message to publish: ")
    if msg == 'exit': os._exit(1)
    pubnub.publish().channel("chan-1").message(str(msg)).pn_async(my_publish_callback)

All of the code in this post is hosted on GitHub in the Python Socket Demo repository.

PubNub is entirely free up to 1 million messages per month. For more capability of the API, check out the PubNub Python v4 SDK documentation, or any of the other 75+ PubNub client SDKs.

Try PubNub today!
Try Our APIs

# data[].attributes.attachment_link.title
Socket Programming in Python: Client, Server, and Peer Examples | PubNub

# data[].attributes.attachment_link.description
Sockets (aka socket programming) enable programs to send and receive data, bi-directionally, at any given moment. This tutorial walks through how you can send data from device-to-device, client-to-server, and vice versa using socket programming in Python. Internet-connected applications that need to operate in realtime greatly benefit from the implementation of sockets in their networking code.

# data[].attributes.attachment_link.readable_text
import smtplib

try:
    server = smtplib.SMTP_SSL('smtp.gmail.com',465)
    #Next, log in to the server
    server.login('mygmailusername@gmail.com', 'mygmailpassword')

    #Send the mail
    msg = 'Hello!' # The /n separates the message from the headers
    server.sendmail('mygmailusername@gmail.com', 'to@gmail.com', msg)
    print('email inviata con successo')
except:
    print("something in the air goes wrong")

# data[].attributes.attachment_link.readable_text
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('0.0.0.0', 5420))
client.send("I am CLIENT\n")
from_server = client.recv(4096)
client.close()
print from_server

# data[].attributes.attachment_link.readable_text
import socket
serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serv.bind(('0.0.0.0', 5420))
serv.listen(5)
while True:
    conn, addr = serv.accept()
    from_client = ''
    while True:
        data = conn.recv(4096)
        if not data: break
        from_client += data
        print from_client
        conn.send("I am SERVER\n")
    conn.close()
    print 'client disconnected'

# data[].attributes.attachment_link.readable_text
# Programma client
import socket

HOST = '0.0.0.0' # Il nodo remoto con nome o IP
PORT = 50000        # La stessa porta usata dal server
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
m = "Hello world"
encodem = m.encode('utf-8')
inviato = s.send(encodem)
if (inviato):
    print ("Ho inviato il messaggio")
s.close()

# data[].attributes.attachment_link.readable_text
# Programma server 
import socket

HOST = '0.0.0.0'       # Nome o IP che rappresenta il server locale
PORT = 50000              # Porta non privilegiata  tra 49152 e 65535
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
print ("Attendo...")
s.listen(1)
conn, addr = s.accept()
print ('si e connesso: ', addr)
while True:
    data = conn.recv(1024)
    if not data:
        break
    else:
        print ("Il client dice: "+ data.decode("utf-8"))
        break

conn.close()

# data[].attributes.attachment_link.readable_text
import tkinter as tk

#inizializziamo globalmente la finestra
window = tk.Tk() 
window.geometry("500x500")
window.title("GUI con TkInter!")
# window.resizable(False, False)
# window.configure(background="white")


#dichiariamo le funzione scatenate al click
#potremmo metterle in un file a parte e suddividere grafica da logica?
def firstprint():
    text = "Hello World!"
    text_output = tk.Label(window, text=text, fg="red", font=("Arial", 16))
    text_output.grid(row=0, column=1, sticky="W")

def secondprint():
    text = "Un altro messaggio!"
    text_output = tk.Label(window, text=text, fg="green", font=("Arial", 16))
    text_output.grid(row=1, column=1, padx=50, sticky="W")

#creiamo i bottoni
first_button = tk.Button(text="Hello!", command=firstprint)
first_button.grid(row=0, column=0, sticky="W")

second_button = tk.Button(text="Altro bottone", command=secondprint)
second_button.grid(row=1, column=0, padx=5, pady=10, sticky="W")



if __name__ == "__main__":
    window.mainloop() 

# data[].attributes.attachment_link.readable_text
The following recipes demonstrate some of the capabilities of the GPIO Zero library. Please note that all recipes are written assuming Python 3. Recipes may work under Python 2, but no guarantees!

2.1. Importing GPIO Zero

In Python, libraries and functions used in a script must be imported by name at the top of the file, with the exception of the functions built into Python by default.

Alternatively, the whole GPIO Zero library can be imported:

In this case, all references to items within GPIO Zero must be prefixed:

2.2. Pin Numbering

This library uses Broadcom (BCM) pin numbering for the GPIO pins, as opposed to physical (BOARD) numbering. Unlike in the RPi.GPIO library, this is not configurable. However, translation from other schemes can be used by providing prefixes to pin numbers (see below).

Any pin marked "GPIO" in the diagram below can be used as a pin number. For example, if an LED was attached to "GPIO17" you would specify the pin number as 17 rather than 11:

If you wish to use physical (BOARD) numbering you can specify the pin number as "BOARD11". If you are familiar with the wiringPi pin numbers (another physical layout) you could use "WPI0" instead. Finally, you can specify pins as "header:number", e.g. "J8:11" meaning physical pin 11 on header J8 (the GPIO header on modern Pis). Hence, the following lines are all equivalent:

Note that these alternate schemes are merely translations. If you request the state of a device on the command line, the associated pin number will always be reported in the Broadcom (BCM) scheme:

Throughout this manual we will use the default integer pin numbers, in the Broadcom (BCM) layout shown above.

2.3. LED

Alternatively:

2.4. LED with variable brightness

Similarly to blinking on and off continuously, a PWMLED can pulse (fade in and out continuously):

2.5. Button

Wait for a button to be pressed before continuing:

Run a function every time the button is pressed:

Note

Note that the line does not run the function , rather it creates a reference to the function to be called when the button is pressed. Accidental use of would set the when_pressed action to (the return value of this function) which would mean nothing happens when the button is pressed.

Similarly, functions can be attached to button releases:

2.6. Button controlled LED

Alternatively:

2.7. Button controlled camera

Using the button press to trigger to take a picture using button.when_pressed = camera.capture would not work because the method requires an parameter. However, this can be achieved using a custom function which requires no parameters:

Another example could use one button to start and stop the camera preview, and another to capture:

2.8. Shutdown button

2.10. LEDBarGraph

Note values are essentially rounded to account for the fact LEDs can only be on or off when (the default).

However, using with allows more precise values using LED brightness:

2.11. Traffic Lights

A full traffic lights system.

Alternatively:

2.12. Push button stop motion

Capture a picture with the camera module every time a button is pressed:

See Push Button Stop Motion for a full resource.

2.13. Reaction Game

When you see the light come on, the first person to press their button wins!

See Quick Reaction Game for a full resource.

2.14. GPIO Music Box

Each button plays a different sound!

See GPIO Music Box for a full resource.

2.15. All on when pressed

While the button is pressed down, the buzzer and all the lights come on.

2.16. Full color LED

2.18. Light sensor

Run a function when the light changes:

2.19. Distance sensor

Note

In the diagram above, the wires leading from the sensor to the breadboard can be omitted; simply plug the sensor directly into the breadboard facing the edge (unfortunately this is difficult to illustrate in the diagram without the sensor's diagram obscuring most of the breadboard!)

Run a function when something gets near the sensor:

2.20. Servo

Control a servo between its minimum, mid-point and maximum positions in sequence:

Use a button to control the servo between its minimum and maximum positions:

Automate the servo to continuously slowly sweep:

2.21. Motors

2.22. Robot

Make a robot with a distance sensor that runs away when things get within 20cm of it:

2.23. Button controlled robot

Use four GPIO buttons as forward/back/left/right controls for a robot:

2.24. Keyboard controlled robot

Use up/down/left/right keys to control a robot:

Note

This recipe uses the standard module. This module requires that Python is running in a terminal in order to work correctly, hence this recipe will not work in environments like IDLE.

If you prefer a version that works under IDLE, the following recipe should suffice:

Note

This recipe uses the third-party module. Install this library with first. Be aware that will only work with local input devices; this recipe will not work over SSH.

2.25. Motion sensor robot

Make a robot drive forward when it detects motion:

Alternatively:

2.26. Potentiometer

Present the value of a potentiometer on an LED bar graph using PWM to represent states that won't "fill" an LED:

2.27. Measure temperature with an ADC

2.28. Full color LED controlled by 3 potentiometers

Wire up three potentiometers (for red, green and blue) and use each of their values to make up the colour of the LED:

Alternatively, the following example is identical, but uses the property rather than a loop:

2.29. Timed heat lamp

If you have a pet (e.g. a tortoise) which requires a heat lamp to be switched on for a certain amount of time each day, you can use an Energenie Pi-mote to remotely control the lamp, and the class to control the timing:

2.30. Internet connection status indicator

You can use a pair of green and red LEDs to indicate whether or not your internet connection is working. Simply use the class to identify whether a ping to google.com is successful. If successful, the green LED is lit, and if not, the red LED is lit:

2.31. CPU Temperature Bar Graph

2.32. More recipes

Continue to:

# data[].attributes.attachment_link.title
2. Basic Recipes - Gpiozero 1.5.1 Documentation

# data[].attributes.attachment_link.description
The following recipes demonstrate some of the capabilities of the GPIO Zero library. Please note that all recipes are written assuming Python 3. Recipes may work under Python 2, but no guarantees! In Python, libraries and functions used in a script must be imported by name at the top of the file, with the exception of the functions built into Python by default.