TCPClient

(inherits from Stream via Client)

TCPClient

Creates a client which can connect to a specified internet IP address and port (defined in the client.connect() function).

Warning:

In most cases, using TCPClient is not recommended. If you want to export data off your device, we recommend using Particle.publish() and webhooks.

  • TCPClient does not itself support HTTP. HTTP requires a 3rd-party library.
  • There is no https library for Particle devices, so you cannot connect to a TLS/SSL encrypted HTTP server. This means your data could be viewed, modified, or redirected as it crosses the Internet.
  • Even if there were, doing a TLS/SSL authentication uses a large amount of data, up to 5 kilobytes per connection. The Particle cloud connection uses DTLS which is able to resume a session with much lower overhead and keep it alive for longer periods of time without having to re-authenticate.
  • It is not possible to maintain TCP connections when the device is in sleep mode.
  • Other protocols such as MQTT are not built-in and require 3rd-party libraries. We recommed using Particle.publish() and webhooks instead of MQTT. Using MQTT without TLS/SSL is not secure. Using MQTT with TLS/SSL will use large amounts of cellular data if also using sleep modes, as the MQTT connection cannot be maintained during sleep and each handshake requires 2 to 5 kilobytes of data.

// SYNTAX
TCPClient client;
// EXAMPLE USAGE

TCPClient client;
byte server[] = { 74, 125, 224, 72 }; // Google
void setup()
{
  // Make sure your Serial Terminal app is closed before powering your device
  Serial.begin(9600);
  // Wait for a USB serial connection for up to 30 seconds
  waitFor(Serial.isConnected, 30000);

  Serial.println("connecting...");

  if (client.connect(server, 80))
  {
    Serial.println("connected");
    client.println("GET /search?q=unicorn HTTP/1.0");
    client.println("Host: www.google.com");
    client.println("Content-Length: 0");
    client.println();
  }
  else
  {
    Serial.println("connection failed");
  }
}

void loop()
{
  if (client.available())
  {
    char c = client.read();
    Serial.print(c);
  }

  if (!client.connected())
  {
    Serial.println();
    Serial.println("disconnecting.");
    client.stop();
    for(;;);
  }
}

Cellular Devices (B-Series SoM, Tracker SoM, Tracker One, Boron, E404X, E-Series, and Electron):

On cellular devices, be careful interacting with web hosts with TCPClient or libraries using TCPClient. These can use a lot of data in a short period of time. To keep the data usage low, use Particle.publish along with webhooks.

Direct TCP, UDP, and DNS do not consume Data Operations from your monthly or yearly quota. However, they do use cellular data and could cause you to exceed the monthly data limit for your account.