# Titanium.Network.Socket.TCP

> TCP socket that implements the `Titanium.IOStream` interface.

- Source: https://titaniumsdk.com/docs/sdk/12.6.1/Titanium.Network.Socket.TCP
- Titanium SDK version: 12.6.1
- Kind: proxy
- Platforms: Android, iPhone, iPad, macOS
- Since: Titanium SDK 1.7
- Extends: Titanium.IOStream
- Inheritance: Titanium.IOStream > Titanium.Proxy

Most socket operations are asynchronous. When you create a socket, you can define
callback functions to receive the results of API calls, as well as to handle incoming
data.

For example, for a client-side socket, you define
[connected](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.TCP.md#connected) and
[error](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.TCP.md#error) callback functions.

To connect to a remote host, call the socket's
[connect](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.TCP.md#connect) method. If the socket connects
successfully, your `connected` callback is invoked, and you can send and receive data
on the socket. If the socket connection fails, your `error` callback is invoked.

After a socket is connected, you can access it like any other [Titanium.IOStream](https://titaniumsdk.com/docs/sdk/Titanium.IOStream.md).
Note that the socket's `read` and `write` methods may block, so in most cases
you should use the asynchronous [read](https://titaniumsdk.com/docs/sdk/Titanium.Stream.md#read), [write](https://titaniumsdk.com/docs/sdk/Titanium.Stream.md#write)
and [pump](https://titaniumsdk.com/docs/sdk/Titanium.Stream.md#pump) methods provided by the [Titanium.Stream](https://titaniumsdk.com/docs/sdk/Titanium.Stream.md) module,
rather than using the socket object's `read` and `write` methods directly.

A familiarity with the basics of BSD socket programming is recommended before using
sockets with Titanium.

Use the [Titanium.Network.Socket.createTCP](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#createTCP) method to create a TCP socket.

## Example: Simple Socket IO using Stream.pump

The following example uses the [pump](Titanium.Stream.pump) method from the <Titanium.Stream>
module to read data from a socket. The `pump` method registers a callback that is
called repeatedly to process incoming data from the socket.

``` js
var socket = Ti.Network.Socket.createTCP({
    host: 'blog.example.com', port: 80,
    connected: function (e) {
        Ti.API.info('Socket opened!');
        Ti.Stream.pump(e.socket, readCallback, 1024, true);
        Ti.Stream.write(socket, Ti.createBuffer({
            value: 'GET http://blog.example.com/index.html HTTP/1.1\r\n\r\n'
        }), writeCallback);
    },
        error: function (e) {
        Ti.API.info('Error (' + e.errorCode + '): ' + e.error);
    },
});
socket.connect();

function writeCallback(e) {
    Ti.API.info('Successfully wrote to socket.');
}

function readCallback(e) {
    if (e.bytesProcessed == -1)
    {
        // Error / EOF on socket. Do any cleanup here.
        ...
    }
    try {
        if(e.buffer) {
            var received = e.buffer.toString();
            Ti.API.info('Received: ' + received);
        } else {
            Ti.API.error('Error: read callback called with no buffer!');
        }
    } catch (ex) {
        Ti.API.error(ex);
    }
}
```

## Example: Listening Socket Example

The following sample shows a trivial example of using a listening
socket. In this case, the application simply sends messages to itself,
using the loopback address.

``` js
// Hostname to listen on/connect to. Here we use the loopback
// address. iOS also supports Ti.Platform.address (the address of
// the WiFi interface).
// Android supports only the loopback address.

var hostname = '127.0.0.1';

var clientSocket = Ti.Network.Socket.createTCP({
    host : hostname,
    port : 40404,
    connected : function(e) {
        Ti.API.info('Client socket connected!');
        Ti.Stream.pump(e.socket, pumpCallback, 1024, true);
        e.socket.write(Ti.createBuffer({
            value : 'A message from a connecting socket.'
        }));
    },
    error : function(e) {
        Ti.API.info('Error (' + e.errorCode + '): ' + e.error);
    }
});

function writeCallback(e) {
    Ti.API.info('Successfully wrote to socket.');
}

function pumpCallback(e) {
    // Has the remote socket closed its end?
    if (e.bytesProcessed < 0) {
        Ti.API.info("Closing client socket.");
        clientSocket.close();
        return;
    }
    try {
        if(e.buffer) {
            var received = e.buffer.toString();
            Ti.API.info('Received: ' + received);
        } else {
            Ti.API.error('Error: read callback called with no buffer!');
        }
    } catch (ex) {
        Ti.API.error(ex);
    }
}

// Create a socket and listen for incoming connections
var listenSocket = Ti.Network.Socket.createTCP({
    host : hostname,
    port : 40404,
    accepted : function(e) {
        // This where you would usually store the newly-connected socket, e.inbound
        // so it can be used for read / write operations elsewhere in the app.
        // In this case, we simply send a message then close the socket.
        Ti.API.info("Listening socket <" + e.socket + "> accepted incoming connection <" + e.inbound + ">");
        e.inbound.write(Ti.createBuffer({
            value : 'You have been connected to a listening socket.\r\n'
        }));
        e.inbound.close();
        // close the accepted socket

    },
    error : function(e) {
        Ti.API.error("Socket <" + e.socket + "> encountered error when listening");
        Ti.API.error(" error code <" + e.errorCode + ">");
        Ti.API.error(" error description <" + e.error + ">");
    }
});
// Starts the socket listening for connections, does not accept them
listenSocket.listen();
Ti.API.info("Listening now...");

// Tells socket to accept the next inbound connection. listenSocket.accepted gets
// called when a connection is accepted via accept()
Ti.API.info("Calling accept.");
listenSocket.accept({
    timeout : 10000
});

// Call connect after a short timeout to ensure the listening socket is ready to go.
Ti.API.info("Setting timer to connect.");
setTimeout(function(e)
{
    Ti.API.info("Calling connect on client socket.");
    clientSocket.connect();
}, 500);
```

## Properties

### accepted

- Type: Callback<AcceptedCallbackArgs>
- Platforms: Android, iPhone, iPad, macOS

Callback to be fired when a listener accepts a connection.

### connected

- Type: Callback<ConnectedCallbackArgs>
- Platforms: Android, iPhone, iPad, macOS

Callback to be fired when the socket enters the "connected" state.

Only invoked following a successful [connect](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.TCP.md#connect)
call.

Can only be modified when this socket is in the [INITIALIZED](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#INITIALIZED) state.

### error

- Type: Callback<ErrorCallbackArgs>
- Platforms: Android, iPhone, iPad, macOS

Callback to be fired when the socket enters the [ERROR](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#ERROR) state.

### host

- Type: String
- Platforms: Android, iPhone, iPad, macOS

The host to connect to or listen on.

Can only be modified when this socket is in the [INITIALIZED](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#INITIALIZED) state.

Supports both IPv4 and IPv6 addresses.

### listenQueueSize

- Type: Number
- Platforms: Android, iPhone, iPad, macOS

Max number of pending incoming connections to be allowed when the socket is in the [LISTENING](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#LISTENING) state.

Any incoming connections received while the max number of pending connections has
been reached will be rejected.

### port

- Type: Number
- Platforms: Android, iPhone, iPad, macOS

The port to connect to or listen on.

Can only be modified when this socket is in the [INITIALIZED](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#INITIALIZED) state.

### secure

- Type: Boolean
- Platforms: Android
- Since: Titanium SDK 12.1.0
- Default: `false`

Creates a secure socket.

### state

- Type: Number
- Platforms: Android, iPhone, iPad, macOS
- Permission: read-only

Current state of the socket.

Accepts: `Titanium.Network.Socket.CLOSED`, `Titanium.Network.Socket.CONNECTED`, `Titanium.Network.Socket.ERROR`, `Titanium.Network.Socket.INITIALIZED`, `Titanium.Network.Socket.LISTENING`

### timeout

- Type: Number
- Platforms: Android, iPhone, iPad, macOS

Timeout, in milliseconds, for `connect` and all `write` operations.

Can only be modified when this socket is in the [INITIALIZED](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#INITIALIZED) state.

## Methods

### accept

- Platforms: Android, iPhone, iPad, macOS

Tells a [LISTENING](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#LISTENING) socket to accept a connection request at the top of a listener's request queue when one becomes available.

Nonblocking; if there are no connections in the queue, sets a flag so that
the socket accepts the next incoming connection immediately.

Takes an argument, an [AcceptDict](https://titaniumsdk.com/docs/sdk/AcceptDict.md) object which assigns options to the new
connection.  If the socket is already flagged to accept the next connection,
the existing accept options will be updated to use the newly specified `options`
object.

The `accepted` callback is called when a new connection is accepted as a result of
calling `accept`. The callback argument holds a reference to a new socket,
representing the accepted connection.

Note that the connected callback is **not** called on the newly created socket.
This is because the socket is created in the
[CONNECTED](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#CONNECTED) state, so it never transitions
to the `CONNECTED` state.

Throws an exception if called on a socket that is not in a
[LISTENING](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#LISTENING) state.

Parameters:

- `options` (AcceptDict): Options to be set on next accepted socket.

### close

- Platforms: Android, iPhone, iPad, macOS

Closes a socket.

Throws exception if the socket is not in a [CONNECTED](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#CONNECTED)
or [LISTENING](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#LISTENING) state. Blocking.

### connect

- Platforms: Android, iPhone, iPad, macOS

Attempts to connect the socket to its host/port.

Throws an exception if the socket is in a [CONNECTED](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#CONNECTED)
or [LISTENING](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#LISTENING) state.
Throws an exception if a valid host and port has not been set on this socket.

Nonblocking; connection attempts are asynchronous.

### listen

- Platforms: Android, iPhone, iPad, macOS

Attempts to start listening on the socket's host/port.

The `listen` call will attempt to listen on the specified host and/or port
property for the socket if they are set.

Nonblocking; may return before the socket is fully open and listening.

If the socket is already in a [LISTENING](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#LISTENING) or
[CONNECTED](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#CONNECTED) state, `listen` throws an exception
and sets the socket state to [ERROR](https://titaniumsdk.com/docs/sdk/Titanium.Network.Socket.md#ERROR), but does
**not** fire the error callback.

Any error encountered after the socket starts listening results in the error
callback being fired.

## Inherited members

11 members are inherited. Each is documented on the type that declares it.

- [Titanium.IOStream](https://titaniumsdk.com/docs/sdk/12.6.1/Titanium.IOStream.md): `isReadable`, `isWritable`, `read`, `write`
- [Titanium.Proxy](https://titaniumsdk.com/docs/sdk/12.6.1/Titanium.Proxy.md): `addEventListener`, `apiName`, `applyProperties`, `bubbleParent`, `fireEvent`, `lifecycleContainer`, `removeEventListener`

---

- This corpus documents Titanium SDK 13.4.1. Anything here that does not name a version describes 13.4.1.
- Titanium is maintained by TiDev. The Appcelerator toolchain is retired: there is no `appc` CLI, no Appcelerator Studio and no hosted build service. The supported CLI is `titanium` on npm, invoked as `ti`.

