Titanium.Network.Socket.TCP
> Titanium.Network.Socket.TCP

TCP socket that implements the Titanium.IOStream interface.

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

For example, for a client-side socket, you define connected and error callback functions.

To connect to a remote host, call the socket's 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. Note that the socket's read and write methods may block, so in most cases you should use the asynchronous read, write and pump methods provided by the Titanium.Stream module, rather than using the socket object's read and write methods directly.

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

Use the Titanium.Network.Socket.createTCP method to create a TCP socket.

Examples

Simple Socket IO using Stream.pump

The following example uses the 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.

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);
    }
}

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.

// 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);
  • 1.7
  • 1.7
  • 1.7
Defined By

Properties

Titanium.Network.Socket.TCP
accepted : Callback<AcceptedCallbackArgs>

Callback to be fired when a listener accepts a connection.

Callback to be fired when a listener accepts a connection.

apiName : Stringreadonly

The name of the API that this proxy corresponds to.

The name of the API that this proxy corresponds to.

The value of this property is the fully qualified name of the API. For example, Button returns Ti.UI.Button.

  • 3.2.0
  • 3.2.0
  • 3.2.0
Indicates if the proxy will bubble an event to its parent. ...

Indicates if the proxy will bubble an event to its parent.

Some proxies (most commonly views) have a relationship to other proxies, often established by the add() method. For example, for a button added to a window, a click event on the button would bubble up to the window. Other common parents are table sections to their rows, table views to their sections, and scrollable views to their views. Set this property to false to disable the bubbling to the proxy's parent.

Default: true

  • 3.0.0
  • 3.0.0
  • 3.0.0
Titanium.Network.Socket.TCP
connected : Callback<ConnectedCallbackArgs>

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

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

Only invoked following a successful connect call.

Can only be modified when this socket is in the INITIALIZED state.

Titanium.Network.Socket.TCP
error : Callback<ErrorCallbackArgs>

Callback to be fired when the socket enters the ERROR state.

Callback to be fired when the socket enters the ERROR state.

Titanium.Network.Socket.TCP
host : String

The host to connect to or listen on.

The host to connect to or listen on.

Can only be modified when this socket is in the INITIALIZED state.

Supports both IPv4 and IPv6 addresses.

The Window or TabGroup whose Activity lifecycle should be triggered on the proxy.

The Window or TabGroup whose Activity lifecycle should be triggered on the proxy.

If this property is set to a Window or TabGroup, then the corresponding Activity lifecycle event callbacks will also be called on the proxy. Proxies that require the activity lifecycle will need this property set to the appropriate containing Window or TabGroup.

  • 3.6.0
Titanium.Network.Socket.TCP
listenQueueSize : Number

Max number of pending incoming connections to be allowed when the socket is in the LISTENING state.

Max number of pending incoming connections to be allowed when the socket is in the LISTENING state.

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

Titanium.Network.Socket.TCP
port : Number

The port to connect to or listen on.

The port to connect to or listen on.

Can only be modified when this socket is in the INITIALIZED state.

Titanium.Network.Socket.TCP
: Numberreadonly
Current state of the socket. ...
Titanium.Network.Socket.TCP
timeout : Number

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

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

Can only be modified when this socket is in the INITIALIZED state.

Defined By

Methods

Titanium.Network.Socket.TCP
( options )
Tells a LISTENING socket to accept a connection request at the top of a listener's request queue when one becomes ava...

Tells a 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 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 state, so it never transitions to the CONNECTED state.

Throws an exception if called on a socket that is not in a LISTENING state.

Parameters

  • options : AcceptDict

    Options to be set on next accepted socket.

Returns

  • void
Adds the specified callback as an event listener for the named event. ...

Adds the specified callback as an event listener for the named event.

Parameters

  • name : String

    Name of the event.

  • callback : Callback<Object>

    Callback function to invoke when the event is fired.

Returns

  • void
Applies the properties to the proxy. ...

Applies the properties to the proxy.

Properties are supplied as a dictionary. Each key-value pair in the object is applied to the proxy such that myproxy[key] = value.

  • 3.0.0
  • 3.0.0
  • 3.0.0

Parameters

  • props : Dictionary

    A dictionary of properties to apply.

Returns

  • void
Titanium.Network.Socket.TCP
( )
Closes a socket. ...

Closes a socket.

Throws exception if the socket is not in a CONNECTED or LISTENING state. Blocking.

Returns

  • void

Overrides: Titanium.IOStream.close

Titanium.Network.Socket.TCP
( )
Attempts to connect the socket to its host/port. ...

Attempts to connect the socket to its host/port.

Throws an exception if the socket is in a CONNECTED or LISTENING state. Throws an exception if a valid host and port has not been set on this socket.

Nonblocking; connection attempts are asynchronous.

Returns

  • void
Fires a synthesized event to any registered listeners. ...

Fires a synthesized event to any registered listeners.

Parameters

  • name : String

    Name of the event.

  • event : Dictionary

    A dictionary of keys and values to add to the Titanium.Event object sent to the listeners.

Returns

  • void
Titanium.Network.Socket.TCP
( ) : Callback<AcceptedCallbackArgs>
Gets the value of the accepted property. ...

Gets the value of the accepted property.

Returns

Gets the value of the apiName property. ...

Gets the value of the apiName property.

  • 3.2.0
  • 3.2.0
  • 3.2.0

Returns

  • String
Gets the value of the bubbleParent property. ...

Gets the value of the bubbleParent property.

  • 3.0.0
  • 3.0.0
  • 3.0.0

Returns

  • Boolean
Titanium.Network.Socket.TCP
( ) : Callback<ConnectedCallbackArgs>
Gets the value of the connected property. ...

Gets the value of the connected property.

Returns

Titanium.Network.Socket.TCP
( ) : Callback<ErrorCallbackArgs>
Gets the value of the error property. ...

Gets the value of the error property.

Returns

Titanium.Network.Socket.TCP
( ) : String
Gets the value of the host property. ...

Gets the value of the host property.

Returns

  • String
Gets the value of the lifecycleContainer property. ...

Gets the value of the lifecycleContainer property.

  • 3.6.0

Returns

Titanium.Network.Socket.TCP
( ) : Number
Gets the value of the listenQueueSize property. ...

Gets the value of the listenQueueSize property.

Returns

  • Number
Titanium.Network.Socket.TCP
( ) : Number
Gets the value of the port property. ...

Gets the value of the port property.

Returns

  • Number
Titanium.Network.Socket.TCP
( ) : Number
Gets the value of the state property. ...

Gets the value of the state property.

Returns

  • Number
Titanium.Network.Socket.TCP
( ) : Number
Gets the value of the timeout property. ...

Gets the value of the timeout property.

Returns

  • Number
Indicates whether this stream is readable. ...

Indicates whether this stream is readable.

Returns

  • Boolean

    True if stream is readable, false otherwise.

Indicates whether this stream is writable. ...

Indicates whether this stream is writable.

Returns

  • Boolean

    True if stream is writable, false otherwise.

Titanium.Network.Socket.TCP
( )
Attempts to start listening on the socket's host/port. ...

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 or CONNECTED state, listen throws an exception and sets the socket state to ERROR, but does not fire the error callback.

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

Returns

  • void
( buffer, [offset], [length] ) : Number
Reads data from this stream into a buffer. ...

Reads data from this stream into a buffer.

If offset and length are specified, data is written into the buffer starting at position offset. Data is read from this stream until one of the following occurs:

  • the end of this stream is reached
  • the end of the buffer is reached
  • a total of length bytes have been read from the stream

If offset and length are omitted, data is written starting at the beginning of the buffer.

Returns the number of bytes read, or -1 if the end of stream was reached before any data was read.

Throws an exception on error. For example, if the offset value is past the last byte of buffer.

This method is synchronous. To perform an asynchronous read on an IOStream, use Titanium.Stream.read.

Parameters

  • buffer : Titanium.Buffer

    Buffer to read stream data into.

  • offset : Number (optional)

    Offset into the buffer to start writing stream data. If specified, length must also be specified.

  • length : Number (optional)

    Maximum number of bytes to read. If specified, offset must also be specified.

Returns

  • Number

    Number of bytes read.

Removes the specified callback as an event listener for the named event. ...

Removes the specified callback as an event listener for the named event.

Multiple listeners can be registered for the same event, so the callback parameter is used to determine which listener to remove.

When adding a listener, you must save a reference to the callback function in order to remove the listener later:

var listener = function() { Ti.API.info("Event listener called."); }
window.addEventListener('click', listener);

To remove the listener, pass in a reference to the callback function:

window.removeEventListener('click', listener);

Parameters

  • name : String

    Name of the event.

  • callback : Callback<Object>

    Callback function to remove. Must be the same function passed to addEventListener.

Returns

  • void
Titanium.Network.Socket.TCP
( accepted )
Sets the value of the accepted property. ...

Sets the value of the accepted property.

Parameters

Returns

  • void
Sets the value of the bubbleParent property. ...

Sets the value of the bubbleParent property.

  • 3.0.0
  • 3.0.0
  • 3.0.0

Parameters

  • bubbleParent : Boolean

    New value for the property.

Returns

  • void
Titanium.Network.Socket.TCP
( connected )
Sets the value of the connected property. ...

Sets the value of the connected property.

Parameters

Returns

  • void
Titanium.Network.Socket.TCP
( error )
Sets the value of the error property. ...

Sets the value of the error property.

Parameters

Returns

  • void
Titanium.Network.Socket.TCP
( host )
Sets the value of the host property. ...

Sets the value of the host property.

Parameters

  • host : String

    New value for the property.

Returns

  • void
Sets the value of the lifecycleContainer property. ...

Sets the value of the lifecycleContainer property.

  • 3.6.0

Parameters

Returns

  • void
Titanium.Network.Socket.TCP
( listenQueueSize )
Sets the value of the listenQueueSize property. ...

Sets the value of the listenQueueSize property.

Parameters

  • listenQueueSize : Number

    New value for the property.

Returns

  • void
Titanium.Network.Socket.TCP
( port )
Sets the value of the port property. ...

Sets the value of the port property.

Parameters

  • port : Number

    New value for the property.

Returns

  • void
Titanium.Network.Socket.TCP
( timeout )
Sets the value of the timeout property. ...

Sets the value of the timeout property.

Parameters

  • timeout : Number

    New value for the property.

Returns

  • void
( buffer, [offset], [length] ) : Number
Writes data from a buffer to this stream. ...

Writes data from a buffer to this stream.

If offset and length are specified, data is read from the buffer starting at offset. Bytes are read from the buffer and written to the stream until:

  • the end of the buffer is reached
  • length bytes have been written
  • the stream returns an error

If offset and length are omitted, all of the data in the buffer is written to this stream.

Returns the number of bytes actually written.

Throws an exception if an error is encountered.

Parameters

  • buffer : Titanium.Buffer

    Buffer to write to this stream.

  • offset : Number (optional)

    Offset in the buffer of the first byte to write to the stream. If specified, length must also be specified.

  • length : Number (optional)

    Maximum number of bytes to write to the stream. If specified, offset must also be specified.

Returns

  • Number

    Number of bytes written.