Skip to content

Instantly share code, notes, and snippets.

@alexdlaird
Last active June 5, 2025 16:21
Show Gist options
  • Save alexdlaird/96d914615910ee692e9d034d0586d132 to your computer and use it in GitHub Desktop.
Save alexdlaird/96d914615910ee692e9d034d0586d132 to your computer and use it in GitHub Desktop.
Simple TCP server/client integration example for pyngrok, full documentation found at https://pyngrok.readthedocs.io/en/latest/integrations.html
# HOST="1.tcp.ngrok.io" PORT=12345 python server.py
import os
import socket
from pyngrok import ngrok
host = os.environ.get("HOST")
port = int(os.environ.get("PORT"))
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind a local socket to the port
server_address = ("", port)
sock.bind(server_address)
sock.listen(1)
# Open a ngrok tunnel to the socket
public_url = ngrok.connect(port, "tcp", options={"remote_addr": "{}:{}".format(host, port))
print("ngrok tunnel \"{}\" -> \"tcp://127.0.0.1:{}/\"".format(public_url, port))
while True:
connection = None
try:
# Wait for a connection
print("\nWaiting for a connection ...")
connection, client_address = sock.accept()
print("... connection established from {}".format(client_address))
# Receive the message, send a response
while True:
data = connection.recv(1024)
if data:
print("Received: {}".format(data.decode("utf-8")))
message = "pong"
print("Sending: {}".format(message))
connection.sendall(message.encode("utf-8"))
else:
break
except KeyboardInterrupt:
print(" Shutting down server.")
if connection:
connection.close()
break
sock.close()
# HOST="1.tcp.ngrok.io" PORT=12345 python client.py
import os
import socket
host = os.environ.get("HOST")
port = int(os.environ.get("PORT"))
# Create a TCP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect to the server with the socket via our ngrok tunnel
server_address = (host, port)
sock.connect(server_address)
print("Connected to {}:{}".format(host, port))
# Send the message
message = "ping"
print("Sending: {}".format(message))
sock.sendall(message.encode("utf-8"))
# Await a response
data_received = 0
data_expected = len(message)
while data_received < data_expected:
data = sock.recv(1024)
data_received += len(data)
print("Received: {}".format(data.decode("utf-8")))
sock.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment