HomeRaspberry PiTalking Raspberries, TCP socket protocol in Phyton

Talking Raspberries, TCP socket protocol in Phyton

Making Raspberry Pi talk to each other in Python

Majority of my communication is handled via AutoRemote. It links my pc, mobile, tablet and Raspberry PI 2 & 3. It’s all good and dandy most of the times until I try to issue a python command to the other RPI. Turns out Raspberry PI TCP socket protocol in python can candle client-host communication well. The socket in python is one of the low-level protocols allowing passing over simple commands between 2 devices over the internet. Communication is very fast, and script handling it is very lightweight.

Raspberry Pi TCP Socket protocol

Before we can use socket with python, we need to install this library on both devices (client and host) to do so simply run this in terminal:

sudo apt-get install socket

After prompt installation you will be able to use socket libraries within your python scripts. Below you can see the sample code that you can use in your creation. More details on the structure of the code in the video.
As you can see from the example below, nothing stops you from writing a simple chat protocol between both devices. Surely it won’t be a Whatsapp competitor, but it is something to explore for sure. Few things to remember:

  • Host connection has to be open, otherwise client will throw an exception
  • Port is linked to specific client and connection, you wont be able to share the connection with other devices
  • If one of the sides terminates, connection is lost and new Host session needs to be started

If you can live with these limitations, Raspberry Pi TCP socket provides you with lightning fast responsiveness. How would you use Raspberry Pi socket protocol?

PYTHON: Client
import socket

HOST = '' # Enter IP or Hostname of your server
PORT = 12345 # Pick an open Port (1000+ recommended), must match the server port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST,PORT))

#Lets loop awaiting for your input
while True:
	command = raw_input('Enter your command: ')
	s.send(command)
	reply = s.recv(1024)
		if reply == 'Terminate':
			break
		print reply
PYTHON: Server
import socket

HOST = '' # Server IP or Hostname
PORT = 12345 # Pick an open Port (1000+ recommended), must match the client sport
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'

#managing error exception
try:
	s.bind((HOST, PORT))
	except socket.error:
	print 'Bind failed '

	s.listen(5)
	print 'Socket awaiting messages'
	(conn, addr) = s.accept()
	print 'Connected'

# awaiting for message
while True:
	data = conn.recv(1024)
	print 'I sent a message back in response to: ' + data
	reply = ''

	# process your message
	if data == 'Hello':
		reply = 'Hi, back!'
		elif data == 'This is important':
		reply = 'OK, I have done the important thing you have asked me!'

	#and so on and on until...
	elif data == 'quit':
		conn.send('Terminating')
		break
	else:
		reply = 'Unknown command'

	# Sending reply
	conn.send(reply)
	conn.close() # Close connections

PayPal

Nothing says "Thank you" better than keeping my coffee jar topped up!

Patreon

Support me on Patreon and get an early access to tutorial files and videos.

image/svg+xml

Bitcoin (BTC)

Use this QR to keep me caffeinated with BTC: 1FwFqqh71mUTENcRe9q4s9AWFgoc8BA9ZU

M5Paper

Programable, ESP32 based awesome dev platform with 4.7 e-ink display by M5Stack

More HATs

client-image
client-image

Argon One M.2

Enclose Raspberry Pi 4 inside this great case with custom I/O, cooling and GPIO and M.2 SSD support

More cases on

client-image
client-image

Best Raspberry Pi Projects

How to use Raspberry PI as WOL (wake on lan) server

0
While you could wake up your PC from a mobile directly, having a dedicated server capable of doing so is the best solution. The reason is simple. You can hook up as many devices as you wish with a single endpoint. This is why Raspberry Pi is perfect for this.

Slow Internet Warning

0
From time to time my Internet grinds to a stop. Since Raspberry Pi 4 comes with a 1Gbps Ethernet, I decided to take advantage of it and create a reporting system in NodeRED that will monitor and report when the ISP is not keeping the contractual agreements. Works with Alexa, Google Home, Android and Windows 10.

How fast Raspberry Pi NAS is?

0
Let's see how fast Raspberry Pi NAS really is?

Argon18: Argon ONE SSD modification

0
Argon One case just got better - now you can boot it from USB without ruining the design thanks to Argon 18: Argon One SSD modification

HOW TO...

It took me 2 months to boot CM4 from NVMe

0
Complete beginners guide to Compute Module 4 boot from NVMe.

Raspberry Pi Zero 2 W vs other Zero boards

0
It's time to test the Raspberry Pi Zero 2 W against other Raspberry Pi boards from Zero series: power, WiFi, temperature and core performance

C/C++ and MicroPython SDK for Raspberry Pi Pico on Windows

0
A guide to SDK toolchain for Raspberry Pi Pico and C/C++ , Micropython on Windows.

A comprehensive guide to Grafana & InfluxDB

0
How to use Grafana and InfluxDB on Raspberry Pi for IoT sensors in home automation

How to boot Raspberry Pi 4 from USB

0
How to set up and boot Raspberry Pi 4 from USB drive - headless guide.