TCP sockets
The Workers runtime provides the connect()
API for creating outbound TCP connections ↗ from Workers.
Many application-layer protocols are built on top of the Transmission Control Protocol (TCP). These application-layer protocols, including SSH, MQTT, SMTP, FTP, IRC, and most database wire protocols including MySQL, PostgreSQL, MongoDB, require an underlying TCP socket API in order to work.
The connect()
function returns a TCP socket, with both a readable and writable stream of data. This allows you to read and write data on an ongoing basis, as long as the connection remains open.
connect()
is provided as a Runtime API, and is accessed by importing the connect
function from cloudflare:sockets
. This process is similar to how one imports built-in modules in Node.js. Refer to the following codeblock for an example of creating a TCP socket, writing to it, and returning the readable side of the socket as a response:
connect(address: SocketAddress | string, options?: optional SocketOptions)
:Socket
connect()
accepts either a URL string orSocketAddress
to define the hostname and port number to connect to, and an optional configuration object,SocketOptions
. It returns an instance of aSocket
.
-
hostname
string- The hostname to connect to. Example:
cloudflare.com
.
- The hostname to connect to. Example:
-
port
number- The port number to connect to. Example:
5432
.
- The port number to connect to. Example:
-
secureTransport
"off" | "on" | "starttls" — Defaults tooff
- Specifies whether or not to use TLS ↗ when creating the TCP socket.
off
— Do not use TLS.on
— Use TLS.starttls
— Do not use TLS initially, but allow the socket to be upgraded to use TLS by callingstartTls()
.
-
allowHalfOpen
boolean — Defaults tofalse
- Defines whether the writable side of the TCP socket will automatically close on end-of-file (EOF). When set to
false
, the writable side of the TCP socket will automatically close on EOF. When set totrue
, the writable side of the TCP socket will remain open on EOF. - This option is similar to that offered by the Node.js
net
module ↗ and allows interoperability with code which utilizes it.
- Defines whether the writable side of the TCP socket will automatically close on end-of-file (EOF). When set to
-
remoteAddress
string | null- The address of the remote peer the socket is connected to. May not always be set.
-
localAddress
string | null- The address of the local network endpoint for this socket. May not always be set.
-
readable
: ReadableStream- Returns the readable side of the TCP socket.
-
writable
: WritableStream- Returns the writable side of the TCP socket.
- The
WritableStream
returned only accepts chunks ofUint8Array
or its views.
-
opened
Promise<SocketInfo>
- This promise is resolved when the socket connection is established and is rejected if the socket encounters an error.
-
closed
Promise<void>
- This promise is resolved when the socket is closed and is rejected if the socket encounters an error.
-
close()
Promise<void>
- Closes the TCP socket. Both the readable and writable streams are forcibly closed.
-
startTls()
: Socket- Upgrades an insecure socket to a secure one that uses TLS, returning a new Socket. Note that in order to call
startTls()
, you must setsecureTransport
tostarttls
when initially callingconnect()
to create the socket.
- Upgrades an insecure socket to a secure one that uses TLS, returning a new Socket. Note that in order to call
Many TCP-based systems, including databases and email servers, require that clients use opportunistic TLS (otherwise known as StartTLS ↗) when connecting. In this pattern, the client first creates an insecure TCP socket, without TLS, and then upgrades it to a secure TCP socket, that uses TLS. The connect()
API simplifies this by providing a method, startTls()
, which returns a new Socket
instance that uses TLS:
startTls()
can only be called ifsecureTransport
is set tostarttls
when creating the initial TCP socket.- Once
startTls()
is called, the initial socket is closed and can no longer be read from or written to. In the example above, anytime afterstartTls()
is called, you would use the newly createdsecureSocket
. Any existing readers and writers based off the original socket will no longer work. You must create new readers and writers from the newly createdsecureSocket
. startTls()
should only be called once on an existing socket.
To handle errors when creating a new TCP socket, reading from a socket, or writing to a socket, wrap these calls inside try..catch
blocks. The following example opens a connection to Google.com, initiates a HTTP request, and returns the response. If any of this fails and throws an exception, it returns a 500
response:
You can close a TCP connection by calling close()
on the socket. This will close both the readable and writable sides of the socket.
- Outbound TCP sockets to Cloudflare IP ranges ↗ are temporarily blocked, but will be re-enabled shortly.
- TCP sockets cannot be created in global scope and shared across requests. You should always create TCP sockets within a handler (ex:
fetch()
,scheduled()
,queue()
) oralarm()
. - Each open TCP socket counts towards the maximum number of open connections that can be simultaneously open.
- By default, Workers cannot create outbound TCP connections on port
25
to send email to SMTP mail servers. Cloudflare Email Workers provides APIs to process and forward email. - Support for handling inbound TCP connections is coming soon ↗. Currently, it is not possible to make an inbound TCP connection to your Worker, for example, by using the
CONNECT
HTTP method.
Review descriptions of common error messages you may see when working with TCP Sockets, what the error messages mean, and how to solve them.
Your socket is connecting to an address that was disallowed. Examples of a disallowed address include Cloudflare IPs, localhost
, and private network IPs.
If you need to connect to addresses on port 80
or 443
to make HTTP requests, use fetch
.
Your socket is connecting back to the Worker that initiated the outbound connection. In other words, the Worker is connecting back to itself. This is currently not supported.
Your socket is connecting to an address on port 25
. This is usually the port used for SMTP mail servers. Workers cannot create outbound connections on port 25
. Consider using Cloudflare Email Workers instead.