TCP Client

TCPClient library for a JavaScript Plugin

Remarks

The example below shows how to build the backend for a simple terminal program.

Example

plugin.Name = "TCPExample";
plugin.OnChangeRequest = onChangeRequest;
plugin.OnConnect = onConnect;
plugin.OnDisconnect = onDisconnect;
plugin.OnPoll = onPoll;
plugin.OnSynchronizeDevices = onSynchronizeDevices;
plugin.PollingInterval = 0;
plugin.DefaultSettings = { "Host": "192.168.1.100", "Port": "23" };
var tcp = new TCPClient();
var tcpDeviceId = "terminal";
function onChangeRequest(device, attribute, value) {
switch (attribute) {
case "TerminalInput":
tcp.send(value);
break;
default:
return;
}
}
function onConnect() {
var host = plugin.Settings["Host"];
var port = plugin.Settings["Port"];
if (host && port) {
tcp.connect(host, parseInt(port));
}
else {
tcp.connect("192.168.1.219", 23);
}
}
function onDisconnect() {
tcp.close();
}
function onPoll() {
while (true) {
//`receive` blocks until a message is received.
//Our message will be a UTF8 encoded string.
//For byte data use this instead.
//var data = tcp.receive({encoding: null});
var data = tcp.receive();
console.log("message received" + data);
var terminalDevice = plugin.Devices[tcpDeviceId];
if (terminalDevice.TerminalOutput != null) {
terminalDevice.TerminalOutput = terminalDevice.TerminalOutput + "\n" + data;
}
else {
terminalDevice.TerminalOutput = data;
}
}
}
function onSynchronizeDevices() {
var terminalDevice = new Device();
terminalDevice.Id = tcpDeviceId;
terminalDevice.DisplayName = "Terminal Device";
terminalDevice.Capabilities = [];
terminalDevice.Attributes = ["TerminalInput", "TerminalOutput"];
plugin.Devices[terminalDevice.Id] = terminalDevice;
}

Methods

connect

Connects the client to the specified port on the specified host.

connect(host, port, [options])

  • host : The IP address or host name to which you intend to connect.
  • port : The port number to which you intend to connect.
  • options
    • timeout : Time, in milliseconds, to wait before timing out. The default is 0 which waits indefinitely.

close

Closes the client connection.

close()

receive

Receives data on the client.

receive([options])

  • options
    • encoding : Defaults to UTF8. Set to null if you wish to receive binary byte data .
    • timeout : Time, in milliseconds, to wait before timing out. The default is 0 which waits indefinitely.

Returns either a message string or bytes depending on the supplied encoding option.

send

Sends data from the client.

send(data, [options])

  • data : The data to send. Can be either a string or a byte array.
  • options
    • encoding : The encoding for string data. The default is UTF8. Ignored if byte data is supplied.
    • timeout : Time, in milliseconds, to wait before timing out. The default is 0 which waits indefinitely.