Raw TCP
Raw TCP from your Pyodide app — for when you want a real socket and a native Python driver.
Raw TCP resources (kind tunnel in the API) expose a raw TCP socket from inside Pyodide. After pycorner.tunnel.install(), pg8000.connect(host="proddb", …) works exactly like it would in plain Python — the socket bytes are tunneled over a WebSocket → your agent → your real on-prem service.
If you can get away with Mode 1 (Database), use that — it’s simpler, has no driver-compatibility constraints, and works for cloud-only services. Raw TCP is for native driver access and wire-level control.
How it works
pg8000.connect(host="proddb", ...)
└── socket.create_connection(("proddb", 5432)) ← intercepted
└── _WsSocket: WebSocket to /ws/x/tunnel/proddb/
└── daphne resolves resource → opens TCP session via agent
└── agent.open_tcp_session → 127.0.0.1:5432 (or wherever)
The Pyodide app’s socket.recv(n) is sync. Browser WebSockets are async. We bridge with pyodide.ffi.run_sync, which blocks the Pyodide worker thread on a Promise using SharedArrayBuffer + Atomics.wait. That’s why the editor sends Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp headers — without cross-origin isolation, SAB isn’t available and the bridge can’t block synchronously.
Create a resource
You need a tunnel agent running on the same network as your target service. If you haven’t installed one, see Tunnel Agent first.
Then on the Resources page, filter by Raw TCP and click New Raw TCP:
- Agent or pool — the tunnel agent that can reach the target, or a pool of agents in that network.
- Target host —
127.0.0.1,10.0.0.5,db.internal.corp, etc. (resolved from the agent’s network, not yours). - Target port — the port of the service.
- Protocol — TCP (the default) or UDP.
The target has to be in the agent’s reachable destinations (Tunnel Agent): a new agent reaches nothing until something is listed. The resource says so when its target is missing, with a button that adds it.
With protocol UDP every binary message on the resource’s WebSocket (/ws/x/tunnel/<name>/) is one datagram, in both directions. pycorner.tunnel.install() patches TCP sockets only.
Use it
import pycorner
pycorner.tunnel.install() # monkey-patches socket.create_connection
import pg8000.dbapi
import streamlit as st
conn = pg8000.dbapi.connect(
host="proddb", # name of the Tunnel resource
port=5432, # placeholder; the resource config wins
database="postgres",
user="postgres",
password="<secret>",
ssl_context=False, # Pyodide has no `ssl` module
)
cur = conn.cursor()
cur.execute("SET search_path TO sample, public")
cur.execute("SELECT * FROM customers WHERE active = true")
rows = cur.fetchall()
st.table(rows) # st.dataframe doesn't render in stlite
requirements.txt:
pg8000
Compatibility notes
ssl_context=Falseis required. pg8000’s default behavior is “try SSL”; in Pyodide that hitsimport sslwhich fails (nosslmodule). pymysql has a similar opt-out (ssl=Noneby default; passssl=Falseto be sure).st.table, notst.dataframe. stlite mocks pyarrow, and Streamlit’s dataframe renderer needs the real pyarrow.socket.create_connectionis the only entry point we patch. Libraries that build their own socket viasocket.socket()+.connect()bypass us — fortunately the major pure-Python drivers (pg8000, pymysql, redis-py) all usecreate_connection.
What about MySQL / Redis / others?
Same pattern. Any pure-Python driver that uses socket.create_connection to a hostname matching one of your Tunnel resource names will route through the bridge:
import pycorner; pycorner.tunnel.install()
import pymysql
conn = pymysql.connect(host="mydb-mysql", port=3306, user="root", password="...")
import redis
r = redis.Redis(host="mycache", port=6379)
C-extension drivers (psycopg2, mysqlclient, hiredis) are not installable in Pyodide — use the pure-Python alternative.
Troubleshooting
Set PYCORNER_DEBUG=1 (or call pycorner.set_debug(True) after install()) before the connect to dump per-byte send/recv plus hex heads of inbound chunks to the browser console. Most issues fall into one of:
- Handshake times out — agent isn’t connected; check the agent’s terminal logs and Resources → Tunnel Agents (online dot).
- WS closes with code 4004 — resource lookup failed (wrong name, or you renamed and didn’t re-save the project).
- WS closes with code 4006 — no session could be opened: the target is not in the agent’s reachable destinations (add it on the Resources page; the resource’s Test button says which destination is missing), the agent’s own
config.jsondoes not allow it, or the agent couldn’t reachtarget_host:portlocally. The agent’s log says which.
When to call pycorner.tunnel.reset()
If a cached pg8000 connection has gone stale (e.g. the preview token expired and the WS was closed server-side), the next query against the cached conn will raise. pycorner.tunnel.reset() closes all live tunnel sockets and removes the monkey-patch — your next pycorner.tunnel.install() re-reads the current token and re-patches:
try:
rows = conn.cursor().execute("SELECT 1").fetchall()
except Exception:
pycorner.tunnel.reset()
get_conn.clear() # if you're using @st.cache_resource
raise # or rerun the script