Server Setup for Testing
The built-in server lets you test your client code without a physical PLC.
Basic Server Example
from s7.server import Server
from s7.type import SrvArea
from ctypes import c_char
# Create and configure the server
server = Server()
# Register a data block (DB1) with 100 bytes
db_size = 100
db_data = bytearray(db_size)
db_array = (c_char * db_size).from_buffer(db_data)
server.register_area(SrvArea.DB, 1, db_array)
# Start the server on a non-privileged port
server.start(tcp_port=1102)
Client-Server Round Trip
from s7 import Client
from s7.server import Server
from s7.type import SrvArea
from ctypes import c_char
# --- Server setup ---
server = Server()
db_size = 100
db_data = bytearray(db_size)
db_array = (c_char * db_size).from_buffer(db_data)
server.register_area(SrvArea.DB, 1, db_array)
server.start(tcp_port=1102)
# --- Client connection ---
client = Client()
client.connect("127.0.0.1", 0, 1, tcp_port=1102)
# Write data
client.db_write(1, 0, bytearray([0x01, 0x02, 0x03, 0x04]))
# Read it back
data = client.db_read(1, 0, 4)
print(f"Read back: {list(data)}") # [1, 2, 3, 4]
# Clean up
client.disconnect()
server.stop()
Registering Multiple Areas
from s7.server import Server
from s7.type import SrvArea
from ctypes import c_char
server = Server()
# Register DB1
db1_data = bytearray(100)
db1 = (c_char * 100).from_buffer(db1_data)
server.register_area(SrvArea.DB, 1, db1)
# Register DB2
db2_data = bytearray(200)
db2 = (c_char * 200).from_buffer(db2_data)
server.register_area(SrvArea.DB, 2, db2)
# Register merker area (256 bytes)
mk_data = bytearray(256)
mk = (c_char * 256).from_buffer(mk_data)
server.register_area(SrvArea.MK, 0, mk)
server.start(tcp_port=1102)
Note
Use a port number above 1024 (e.g., 1102) to avoid requiring root/admin privileges. Port 102 is the standard S7 port but is in the privileged range.
Read-only Areas
Pass read_only=True to make the server refuse client writes to an area.
Reads keep working, and the server side can still change the data.
server.register_area(SrvArea.DB, 1, bytearray(100), read_only=True)
A write (Write Var) to such an area is answered with item return code 0x03,
“accessing the object not allowed”, and no error in the header. The client
raises S7ProtocolError for it. This is what an S7-1214C (firmware V4.2)
answers for a write to a write-protected DB; S7-300/400 has not been captured.
A block download to a read-only DB is not refused.
Using the Mainloop Helper
For quick testing, the mainloop function from the s7 package
starts a server with common data blocks pre-registered:
from s7.server import mainloop
# Blocks the current thread
mainloop(tcp_port=1102)