- Open Git Bash.
- Clone.
git clone https://github.com/HoningLo/Python-TCP-IP-Communication.git
cd Python-TCP-IP-Communication
- Python >= 3.6
Create a virtual environment:
python -m venv venv
# Windows
.\venv\scripts\activate
# Linux
source venv/bin/activate
Install the dependencies:
pip install -r requirements.txt
Linux:
./install.sh
Run the main.py
:
python main.py
Browse to the sample application at http://localhost:9527
in a web browser.
Edit the file main.py
and replace the parameters HOST
and PORT
with your specific IP address and port number.
# main.py
...
...
...
if __name__ == '__main__':
HOST = "localhost"
PORT = 9527
uvicorn.run(app, host=HOST, port=PORT)
Edit the file Requests_WebAPI.py
and replace the text ____Enter_Your_DeviceID____
, ____Enter_Your_URL____
with your DeviceID and your URL.
# main.py
...
url = "____Enter_Your_URL____"
...
data = {"DeviceID": "____Enter_Your_DeviceID____"}
...
Run the Requests_WebAPI.py
:
python Requests_WebAPI.py
Result:
Edit the file Socket_Server.py
and replace the parameters HOST
and PORT
with your specific IP address and port number.
# Socket_Server.py
...
...
...
if __name__ == '__main__':
HOST = "localhost"
PORT = 9527
build_server(HOST, PORT)
Run the Socket_Server.py
:
python Socket_Server.py
Edit the file Socket_Client.py
and replace the parameters HOST
and PORT
with your specific IP address and port number.
# Socket_Client.py
...
...
...
if __name__ == '__main__':
HOST = "localhost"
PORT = 9527
send_message(HOST, PORT)
Run the Socket_Client.py
:
python Socket_Client.py
Server Result:
Client Result:
Edit the file ModbusTCP_Server.py
and replace the parameters HOST
and PORT
with your specific IP address and port number.
# ModbusTCP_Server.py
...
...
...
if __name__ == '__main__':
HOST = "localhost"
PORT = 9527
build_server(HOST, PORT)
Run the ModbusTCP_Server.py
:
python ModbusTCP_Server.py
Edit the file ModbusTCP_Client.py
and replace the parameters HOST
and PORT
with your specific IP address and port number.
# ModbusTCP_Client.py
...
...
...
if __name__ == '__main__':
HOST = "localhost"
PORT = 9527
modbus_client = Modbus_Client(HOST, PORT)
modbus_client.read_holding_registers(0)
modbus_client.write_single_register(1, 111)
modbus_client.write_multiple_registers(2, [222, 333, 444])
Run the ModbusTCP_Client.py
:
python ModbusTCP_Client.py
Server Result:
Client Result:
Python Socket - Python network programming with sockets (zetcode.com)
[Python] 使用 socket 模組基本教學 - Clay-Technology World (clay-atlas.com)