DEV Community

HarmonyOS
HarmonyOS

Posted on

How to connect another device by using TCP Socket?

Read the original article:How to connect another device by using TCP Socket?

Context

Connecting two devices using a TCP (Transmission Control Protocol) socket allows them to exchange data reliably over a network. TCP ensures that data packets are delivered in order and without loss, which makes it suitable for applications such as chat systems, file transfers, or real-time communication.

Description

Using HarmonyOS Network Kit, you can establish a TCP socket connection between your smartwatch and another device (such as a computer) within the same local network. The socket connection enables direct data exchange by using the target device’s IP address and port number.

When the connection is established:

  • The smartwatch acts as a client, initiating a request to the computer.
  • The computer runs a socket server, waiting for incoming connections.
  • Once connected, both devices can send and receive data streams in real time.

This approach is commonly used for scenarios such as remote monitoring, sending commands from the watch to the PC, or synchronizing data across devices in a local Wi-Fi network.

Solution / Approach

To establish a connection from a HarmonyOS smartwatch to a computer on the same local network, you can use the Network Kit TCP Socket API.
The process involves four main steps:

  1. Create and configure a TCP socket instance
  2. Bind the socket to a local network interface
  3. Connect to the remote device (PC) using its IP and port
  4. Handle socket events (connect, message, close, error)

Create the TCP Socket Instance

First, construct a TCP socket instance that will be responsible for the connection.

private tcp: socket.TCPSocket = socket.constructTCPSocketInstance();
private remoteIP: string = '';
private remotePort: number = 12345; // TARGET PORT
Enter fullscreen mode Exit fullscreen mode

Bind to a Local Address

Before connecting, the socket must be bound to a local address.
Using 0.0.0.0 ensures that all available network interfaces can be used.

let localAddress: socket.NetAddress = {
  address: '0.0.0.0',
  port: 0 // System assigns a free port automatically
};

this.tcp.bind(localAddress, (err: BusinessError) => {
  if (err) {
    console.error('Bind error: ' + JSON.stringify(err));
    this.statusMessage = 'Bind error';
    return;
  }
  console.log('Bind successful');
});
Enter fullscreen mode Exit fullscreen mode

Connect to the Remote Device

After binding, connect to the PC’s IP address and listening port.
You can configure a timeout for the connection attempt.

let remoteAddress: socket.NetAddress = {
  address: this.remoteIP, // entered by the user
  port: this.remotePort
};

let connectOptions: socket.TCPConnectOptions = {
  address: remoteAddress,
  timeout: 5000
};

this.tcp.connect(connectOptions).then(() => {
  console.log('Connection successful');
  this.isConnected = true;
  this.statusMessage = 'Connected! ✓';
}).catch((err: BusinessError) => {
  console.error('Connection error: ' + JSON.stringify(err));
  this.statusMessage = 'Connection Error!';
});
Enter fullscreen mode Exit fullscreen mode

Handle Socket Events

It’s important to manage lifecycle events such as message reception, connection establishment, closure, and errors.

this.tcp.on('message', (value: SocketInfo) => {
  console.log("Message received");
});

this.tcp.on('connect', () => {
  console.log("Connection established");
  this.isConnected = true;
  this.statusMessage = 'Connected Successfully! ✓';
});

this.tcp.on('close', () => {
  console.log("Connection closed");
  this.isConnected = false;
  this.statusMessage = 'Connection Lost';
});

this.tcp.on('error', (err: BusinessError) => {
  console.error("Socket error: " + JSON.stringify(err));
  this.statusMessage = 'Connection Error!';
});
Enter fullscreen mode Exit fullscreen mode

Disconnect and Cleanup

Always close the socket when the app is stopped or when the user disconnects manually.

this.tcp.close().then(() => {
  console.log('Connection closed');
  this.isConnected = false;
  this.statusMessage = 'Connection Lost';
}).catch((err: BusinessError) => {
  console.error('Close error: ' + JSON.stringify(err));
});
Enter fullscreen mode Exit fullscreen mode

Here you can find the related screenshots below;

image.pngimage.pngimage.pngimage.png

Key Takeaways

  • HarmonyOS Network Kit allows creating and managing TCP socket connections directly from a smartwatch.
  • The smartwatch acts as a TCP client, while the computer (or another device) must run a TCP server to accept incoming connections.
  • A local bind (0.0.0.0) ensures the socket can use any available network interface.
  • Connecting requires the remote device’s IP address and port to be known and accessible.
  • Proper handling of socket events (connect, message, close, error) ensures a stable and user-friendly experience.
  • Always close the socket when the app exits or when the user disconnects to prevent resource leaks.
  • Both devices must be on the same Wi-Fi/local network, and firewall rules on the PC must allow incoming connections.

Additional Resources

https://developer.huawei.com/consumer/en/doc/harmonyos-guides/socket-connection

Written by Mehmet Algul

Top comments (0)