# mulesoft Sockets Connector - Full Documentation --- product: Sockets Connector version: 1.2 is-latest-version: true --- # Sockets Connector 1.2 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Anypoint Connector for Sockets (Sockets Connector) provides a sockets listener, send capability, and send and receive functionality. Additionally, it provides TCP and UDP requesters. ## Before You Begin To use this connector, you must be familiar with: - Anypoint Connectors - Mule runtime engine (Mule) - Elements in a Mule flow - Global elements - Creating a Mule app using Anypoint Studio Before creating an app, you must have access to Anypoint Platform and Anypoint Studio. ## Audience - New user, read: - [Using Anypoint Studio to Configure the Connector](https://docs.mulesoft.com/sockets-connector/latest/sockets-connector-studio) to create your Mule app - [Examples](https://docs.mulesoft.com/sockets-connector/latest/sockets-connector-examples), which provides one or more use cases for the connector - Advanced user, read: - [XML and Maven Support](https://docs.mulesoft.com/sockets-connector/latest/sockets-connector-xml-maven) - [Examples](https://docs.mulesoft.com/sockets-connector/latest/sockets-connector-examples), which provides one or more use cases for the connector ## See Also - [Introduction to Anypoint Connectors](https://docs.mulesoft.com/connectors/introduction/introduction-to-anypoint-connectors) - [Use Exchange to Discover Connectors, Templates, and Examples](https://docs.mulesoft.com/connectors/introduction/intro-use-exchange) - [Sockets Connector in Exchange](https://anypoint.mulesoft.com/exchange/org.mule.connectors/mule-sockets-connector/) - [Salesforce Help](https://help.salesforce.com) --- product: Sockets Connector version: 1.2 is-latest-version: true --- # Sockets Connector Reference > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Sockets Connector v1.2 Anypoint Connector for Sockets (Sockets Connector) provides a sockets listener, send capability, and send and receive functionality. Provides TCP and UDP requesters. Release Notes: [Sockets Connector Release Notes](https://docs.mulesoft.com/release-notes/connector/connector-sockets) ## Configurations --- ### Listener Config Config for listener sockets #### Parameters
NameTypeDescriptionDefault ValueRequired

Name

String

The name for this configuration. Connectors reference the configuration with this name.

x

Connection

The connection types to provide to this configuration.

x

Expiration Policy

Configures the minimum amount of time that a dynamic configuration instance can remain idle before Mule considers it eligible for expiration. This does not mean that the platform expires the instance at the exact moment that it becomes eligible. Mule purges the instances as appropriate.

#### Connection Types ##### Tcp Listener A ConnectionProvider which provides instances of TcpListenerConnection to use by SocketListener ###### Parameters
NameTypeDescriptionDefault ValueRequired

Protocol

One of:

TcpProtocol that knows how the data is read and written. If not specified, uses SafeProtocol.

TLS Configuration

Implies the use of SSLServerSocket instead of plain TCP ServerSocket for accepting new SSL connections.

Port

Number

Connection’s port number

x

Host

String

Connection’s host name

x

Reconnection

When the application is deployed, a connectivity test is performed on all connectors. If set to true, deployment fails if the test doesn’t pass after exhausting the associated reconnection strategy.

Send Buffer Size

Number

The size of the buffer (in bytes) used when sending data, set on the socket itself.

Receive Buffer Size

Number

The size of the buffer (in bytes) used when receiving data, set on the socket itself.

Client Timeout

Number

Sets the SO_TIMEOUT value on sockets, and indicates the amount of time (in milliseconds) that the socket waits in a blocking operation before failing. A value of 0 (default) indicates waiting indefinitely.

Reuse Address

Boolean

Sets SO_REUSEADDRESS (default) value on the sockets before binding, which helps reduce "address already in use" errors when a socket is reused.

true

Send TCP With No Delay

Boolean

If set, it does not collect transmitted data together for greater efficiency but sends it immediately. Defaults to true even though socket default is false, because optimizing to reduce amount of network traffic over latency is hardly ever a concern today.

true

Linger

Number

Sets SO_LINGER value, and indicates how long (in milliseconds) the socket takes to close, so any remaining data transmits correctly.

Keep Alive

Boolean

Enables SO_KEEPALIVE behavior on open sockets. This automatically checks open socket connections but unused for long periods and closes them if the connection becomes unavailable. This is a property on the socket itself and a server socket uses it to control whether connections to the server keep alive before they recycle.

false

Fail On Unresolved Host

Boolean

Whether the socket fails during its creation if the host set on the endpoint cannot be resolved. However, set it to false to allow unresolved hosts, which is useful when connecting through a proxy.

true

Server Timeout

Number

Sets SO_TIMEOUT value when you use the socket as a server. The timeout that applies to the "accept" operation. If no connection arrives, a value of 0 (default) causes the accept to wait indefinitely.

Receive Backlog

Number

The maximum queue length for incoming connections.

50

##### UDP Listener A ConnectionProvider which provides instances of UdpListenerConnection to use by SocketListener ###### Parameters
NameTypeDescriptionDefault ValueRequired

Port

Number

Connection’s port number

x

Host

String

Connection’s host name

x

Reconnection

When the application is deployed, a connectivity test is performed on all connectors. If set to true, deployment fails if the test doesn’t pass after exhausting the associated reconnection strategy.

Send Buffer Size

Number

The size of the buffer (in bytes) used when sending data, set on the socket itself.

Receive Buffer Size

Number

The size of the buffer (in bytes) used when receiving data, set on the socket itself.

Client Timeout

Number

Sets the SO_TIMEOUT value on sockets, and indicates the amount of time (in milliseconds) that the socket waits in a blocking operation before failing. A value of 0 (default) indicates waiting indefinitely.

Reuse Address

Boolean

Sets SO_REUSEADDRESS (default) value on the sockets before binding, which helps reduce "address already in use" errors when a socket is reused.

true

Broadcast

Boolean

Enable or disable SO_BROADCAST value into the DatagramSocket

false

#### Associated Sources - [Listener](#listener) --- ### Request Config Config for requester sockets #### Parameters
NameTypeDescriptionDefault ValueRequired

Name

String

The name for this configuration. Connectors reference the configuration with this name.

x

Connection

The connection types to provide to this configuration.

x

Expiration Policy

Configures the minimum amount of time that a dynamic configuration instance can remain idle before Mule considers it eligible for expiration. This does not mean that the platform expires the instance at the exact moment that it becomes eligible. Mule purges the instances as appropriate.

#### Connection Types ##### Tcp Requester A ConnectionProvider which provides instances of TcpRequesterConnection to use by the SocketOperations ###### Parameters
NameTypeDescriptionDefault ValueRequired

Local Address Settings

This configuration parameter refers to the address where the Socket should bind to.

Protocol

One of:

TcpProtocol that knows how the data is read and written. If not specified, the SafeProtocol will be used.

TLS Configuration

Implies the use of SSLServerSocket instead of plain TCP ServerSocket for accepting new SSL connections.

Port

Number

Connection’s port number

x

Host

String

Connection’s host name

x

Reconnection

When the application is deployed, a connectivity test is performed on all connectors. If set to true, deployment fails if the test doesn’t pass after exhausting the associated reconnection strategy.

Pooling Profile

Characteristics of the connection pool

Send Buffer Size

Number

The size of the buffer (in bytes) used when sending data, set on the socket itself.

Receive Buffer Size

Number

The size of the buffer (in bytes) used when receiving data, set on the socket itself.

Client Timeout

Number

Sets the SO_TIMEOUT value on sockets, and indicates the amount of time (in milliseconds) that the socket waits in a blocking operation before failing. A value of 0 (default) indicates waiting indefinitely.

Reuse Address

Boolean

Sets SO_REUSEADDRESS (default) value on the sockets before binding, which helps reduce "address already in use" errors when a socket is reused.

true

Send TCP With No Delay

Boolean

If set, it does not collect transmitted data together for greater efficiency but sends it immediately. Defaults to true even though socket default is false, because optimizing to reduce amount of network traffic over latency is hardly ever a concern today.

true

Linger

Number

Sets SO_LINGER value, and indicates how long (in milliseconds) the socket takes to close, so any remaining data transmits correctly.

Keep Alive

Boolean

Enables SO_KEEPALIVE behavior on open sockets. This automatically checks open socket connections but unused for long periods and closes them if the connection becomes unavailable. This is a property on the socket itself and a server socket uses it to control whether connections to the server keep alive before they recycle.

false

Fail On Unresolved Host

Boolean

Whether the socket fails during its creation and if the host set on the endpoint cannot be resolved. However, set it to false to allow unresolved hosts, which is useful when connecting through a proxy.

true

Connection Timeout

Number

Number of milliseconds to wait until an outbound connection to a remote server is successfully created. Defaults to 30 seconds.

30

##### UDP Requester A ConnectionProvider which provides instances of UdpRequesterConnection to use by the SocketOperations ###### Parameters
NameTypeDescriptionDefault ValueRequired

Local Address Settings

This configuration parameter refers to the address where the DatagramSocket should bind to.

Port

Number

Connection’s port number

x

Host

String

Connection’s host name

x

Reconnection

When the application is deployed, a connectivity test is performed on all connectors. If set to true, deployment fails if the test doesn’t pass after exhausting the associated reconnection strategy.

Pooling Profile

Characteristics of the connection pool

Send Buffer Size

Number

The size of the buffer (in bytes) used when sending data, set on the socket itself.

Receive Buffer Size

Number

The size of the buffer (in bytes) used when receiving data, set on the socket itself.

Client Timeout

Number

Sets the SO_TIMEOUT value on sockets, and indicates the amount of time (in milliseconds) that the socket waits in a blocking operation before failing. A value of 0 (default) indicates waiting indefinitely.

Reuse Address

Boolean

Sets SO_REUSEADDRESS (default) value on the sockets before binding, which helps reduce "address already in use" errors when a socket is reused.

true

Broadcast

Boolean

Enable or disable SO_BROADCAST value into the DatagramSocket

false

## Supported Operations - [Send](#send) - [Send And Receive](#sendAndReceive) ## Operations ### Send `` Sends the data using the client associated to the RequesterConnection. #### Parameters
NameTypeDescriptionDefault ValueRequired

Configuration

String

The name of the configuration to use.

x

Content

Binary

data that will be serialized and sent through the socket.

#[payload]

Reconnection Strategy

A retry strategy in case of connectivity errors

### For Configurations - [Request Config](#request-config) #### Throws - SOCKETS:UNKNOWN\_HOST - SOCKETS:CONNECTIVITY - SOCKETS:CONNECTION\_TIMEOUT - SOCKETS:RETRY\_EXHAUSTED - SOCKETS:LENGTH\_EXCEEDED ### Send And Receive `` Sends the data using the client associated to the RequesterConnection and then blocks until a response is received or the timeout is met, in which case the operation returns a null payload. #### Parameters
NameTypeDescriptionDefault ValueRequired

Configuration

String

The name of the configuration to use.

x

Content

Binary

data that will be serialized and sent through the socket.

#[payload]

Output Mime Type

String

The mime type of the payload that this operation outputs.

Output Encoding

String

The encoding of the payload that this operation outputs.

Streaming Strategy

Configure if repeatable streams should be used and their behavior

Target Variable

String

The name of a variable to store the operation’s output.

Target Value

String

An expression to evaluate against the operation’s output and store the expression outcome in the target variable

#[payload]

Reconnection Strategy

A retry strategy in case of connectivity errors

#### Output

Type

Binary

Attributes Type

### For Configurations - [Request Config](#request-config) #### Throws - SOCKETS:UNKNOWN\_HOST - SOCKETS:CONNECTIVITY - SOCKETS:CONNECTION\_TIMEOUT - SOCKETS:RETRY\_EXHAUSTED - SOCKETS:LENGTH\_EXCEEDED ## Sources ### Listener `` Listens for socket connections of the given protocol in the configured host and port. Whenever a new connection is received, this Source will schedule a SocketWorker that will handle the communication for that particular connection. #### Parameters
NameTypeDescriptionDefault ValueRequired

Configuration

String

The name of the configuration to use.

x

Output Mime Type

String

The mime type of the payload that this operation outputs.

Output Encoding

String

The encoding of the payload that this operation outputs.

Primary Node Only

Boolean

Whether this source should only executes on the primary node when running in a cluster

Streaming Strategy

Configure if repeatable streams should be used and their behavior

Redelivery Policy

Defines a policy for processing the redelivery of the same message

Reconnection Strategy

A retry strategy in case of connectivity errors

Response Value

Binary

#[payload]

#### Output

Type

Binary

Attributes Type

### For Configurations - [Listener Config](#listener-config) ## Types ### Tls
FieldTypeDescriptionDefault ValueRequired

Enabled Protocols

String

A comma-separated list of protocols enabled for this context.

Enabled Cipher Suites

String

A comma-separated list of cipher suites enabled for this context.

Trust Store

Key Store

Revocation Check

### Trust Store
FieldTypeDescriptionDefault ValueRequired

Path

String

The location of the trust store. This location resolves relative to the current classpath and file system, if possible.

Password

String

The password used to protect the trust store.

Type

String

The type of store used.

Algorithm

String

The algorithm used by the trust store.

Insecure

Boolean

If true, no certificate validations are performed, rendering connections vulnerable to attacks. Use at your own risk.

### Key Store
FieldTypeDescriptionDefault ValueRequired

Path

String

The location of the trust store. This location resolves relative to the current classpath and file system, if possible.

Type

String

The type of store used.

Alias

String

When the key store contains many private keys, this attribute indicates the alias of the key to use. If not defined, the first key in the file is used by default.

Key Password

String

The password used to protect the private key.

Password

String

The password used to protect the key store.

Algorithm

String

The algorithm used by the key store.

### Standard Revocation Check
FieldTypeDescriptionDefault ValueRequired

Only End Entities

Boolean

Only verify the last element of the certificate chain.

Prefer Crls

Boolean

Try CRL instead of OCSP first.

No Fallback

Boolean

Do not use the secondary checking method.

Soft Fail

Boolean

Avoid verification failure when the revocation server can not be reached or is busy.

### Custom Ocsp Responder
FieldTypeDescriptionDefault ValueRequired

Url

String

The URL of the OCSP responder.

Cert Alias

String

Alias of the signing certificate for the OCSP response (must be in the trust store), if present.

### Crl File
FieldTypeDescriptionDefault ValueRequired

Path

String

The path to the CRL file.

### Reconnection
FieldTypeDescriptionDefault ValueRequired

Fails Deployment

Boolean

When the application is deployed, a connectivity test is performed on all connectors. If set to true, deployment fails if the test doesn’t pass after exhausting the associated reconnection strategy.

Reconnection Strategy

The reconnection strategy to use.

### Reconnect
FieldTypeDescriptionDefault ValueRequired

Frequency

Number

How often in milliseconds to reconnect

Count

Number

How many reconnection attempts to make.

### Reconnect Forever
FieldTypeDescriptionDefault ValueRequired

Frequency

Number

How often in milliseconds to reconnect

### Expiration Policy
FieldTypeDescriptionDefault ValueRequired

Max Idle Time

Number

A scalar time value for the maximum amount of time a dynamic configuration instance should be allowed to be idle before it’s considered eligible for expiration

Time Unit

Enumeration, one of:

  • NANOSECONDS

  • MICROSECONDS

  • MILLISECONDS

  • SECONDS

  • MINUTES

  • HOURS

  • DAYS

A time unit that qualifies the maxIdleTime attribute

### Immutable Socket Attributes
FieldTypeDescriptionDefault ValueRequired

Port

Number

x

Host Address

String

x

Host Name

String

x

Local Certificates

Array of Any

The SSL local certificates. If the Socket is not an SSL Sockets, this is null.

Peer Certificates

Array of Any

The SSL peer certificates. If the Socket is not an SSL Sockets, this is null.

### Repeatable In Memory Stream
FieldTypeDescriptionDefault ValueRequired

Initial Buffer Size

Number

The allocated amount of memory to consume the stream and provide random access to it. If the stream contains more data than can be fit into this buffer, then the buffer expands according to the bufferSizeIncrement attribute, with an upper limit of maxInMemorySize.

Buffer Size Increment

Number

This is by how much the buffer size expands if it exceeds its initial size. Setting a value of zero or lower means that the buffer does not expand, and STREAM_MAXIMUM_SIZE_EXCEEDED error is raised when the buffer gets full.

Max Buffer Size

Number

The maximum amount of memory to use. If more than that is used then a STREAM_MAXIMUM_SIZE_EXCEEDED error is raised. A value lower than or equal to zero means no limit.

Buffer Unit

Enumeration, one of:

  • BYTE

  • KB

  • MB

  • GB

The unit in which all these attributes are expressed

### Repeatable File Store Stream
FieldTypeDescriptionDefault ValueRequired

In Memory Size

Number

Defines the maximum memory that the stream should use to keep data in memory. If more than that is consumed content on the disk is buffered.

Buffer Unit

Enumeration, one of:

  • BYTE

  • KB

  • MB

  • GB

The unit in which maxInMemorySize is expressed

### Redelivery Policy
FieldTypeDescriptionDefault ValueRequired

Max Redelivery Count

Number

The maximum number of times a message can be redelivered and processed unsuccessfully before triggering process-failed-message

Use Secure Hash

Boolean

Whether to use a secure hash algorithm to identify a redelivered message.

Message Digest Algorithm

String

The secure hashing algorithm to use. If not set, defaults to SHA-256.

Id Expression

String

Defines one or more expressions to use to determine when a message is redelivered. This property may only be set if useSecureHash is false.

Object Store

Object Store

The object store to store the redelivery counter for each message.

### Socket Connection Settings
FieldTypeDescriptionDefault ValueRequired

Port

Number

Connection’s port number

x

Host

String

Connection’s host name

x

### Pooling Profile
FieldTypeDescriptionDefault ValueRequired

Max Active

Number

Controls the maximum number of Mule components that can be borrowed from a session at one time. When set to a negative value, there is no limit to the number of components that can be active at one time. When maxActive is exceeded, the pool exhausts.

Max Idle

Number

Controls the maximum number of Mule components that can sit idle in the pool at any time. When set to a negative value, there is no limit to the number of Mule components that can be idle at one time.

Max Wait

Number

Specifies the number of milliseconds to wait for a pooled component to become available when the pool is exhausted and the exhaustedAction is set to WHEN_EXHAUSTED_WAIT.

Min Eviction Millis

Number

Determines the minimum amount of time an object may sit idle in the pool before it is eligible for eviction. When nonpositive, no objects will be evicted from the pool due to idle time alone.

Eviction Check Interval Millis

Number

Specifies the number of milliseconds between runs of the object evictor. When non-positive, no object evictor is executed.

Exhausted Action

Enumeration, one of:

  • WHEN_EXHAUSTED_GROW

  • WHEN_EXHAUSTED_WAIT

  • WHEN_EXHAUSTED_FAIL

Specifies the behavior of the Mule component pool when the pool is exhausted. Possible values are: WHEN_EXHAUSTED_FAIL, which throws a NoSuchElementException, WHEN_EXHAUSTED_WAIT, which blocks by invoking Object.wait(long) until a new or idle object is available, or WHEN_EXHAUSTED_GROW, which creates a new Mule instance and return it, essentially making maxActive meaningless. If a positive maxWait value is supplied, it blocks for at most that many milliseconds, after which a NoSuchElementException will be thrown. If maxThreadWait is a negative value, it blocks indefinitely.

Initialisation Policy

Enumeration, one of:

  • INITIALISE_NONE

  • INITIALISE_ONE

  • INITIALISE_ALL

Determines how components in a pool can initialize. The possible values are INITIALISE_NONE does not load any components into the pool on startup, INITIALISE_ONE loads one initial component into the pool on startup, or INITIALISE_ALL loads all components in the pool on startup

Disabled

Boolean

Whether pooling should be disabled

### Safe Protocol This test protocol precedes every message with a cookie, and should not be used in production environments.
FieldTypeDescriptionDefault ValueRequired

Max Message Length

Number

Indicates the maximum length of the message.

-1

Encoding

String

Indicates the encoding used for serializing the cookie

Rethrow Exception On Read

Boolean

Indicates if the exception should be rethrown if there is a failure while reading

false

### Direct Protocol This protocol allows the socket to read until no more bytes are immediately available. On slow networks, `EOFProtocol` and `LengthProtocol` might be more reliable.
FieldTypeDescriptionDefault ValueRequired

Rethrow Exception On Read

Boolean

Indicates if the exception should be rethrown if there is a failure while reading

false

### Length Protocol This protocol is defined by sending or reading an integer (the packet length) and then the data to transfer.
FieldTypeDescriptionDefault ValueRequired

Max Message Length

Number

Indicates the maximum length of the message.

-1

Rethrow Exception On Read

Boolean

Indicates if the exception should be rethrown if there is a failure while reading

false

### Streaming Protocol This protocol allows the socket’s Send operation to return a message with the original InputStream as payload.
FieldTypeDescriptionDefault ValueRequired

Rethrow Exception On Read

Boolean

Indicates if the exception should be rethrown if there is a failure while reading

false

### XML Message Protocol This protocol reads streaming XML documents. The only requirement is that each document includes an XML declaration at the beginning of the document in the form of ` FieldTypeDescriptionDefault ValueRequired

Rethrow Exception On Read

Boolean

Indicates if the exception should be rethrown if there is a failure while reading

false

### XML Message Eof Protocol This protocol extends `XmlMessageProtocol` to continue reading until either a new message or EOF is found.
FieldTypeDescriptionDefault ValueRequired

Rethrow Exception On Read

Boolean

Indicates if the exception should be rethrown if there is a failure while reading

false

### Custom Protocol Define your own custom protocol by writing a class that extends `TcpProtocol`.
FieldTypeDescriptionDefault ValueRequired

Class

String

Reference to full qualifier class name that should extend TcpProtocol to use as a custom protocol

x

### Eof Protocol When clients connect to a server using the EOF protocol, they write the message on the socket connection output stream. To signal the end of the message, clients must signal the end of file (EOF) by closing the output stream and keeping the input stream open, waiting for a response from the server. This behavior is known as half-close. Then, the server sends a response and closes its output stream and the whole socket connection. For TLS secured connections, use TLS 1.3 and JDK 11 as the half-close feature is not supported in TLS 1.2 and earlier versions. The half-close feature triggers the close notification alert to prevent TLS truncation attacks. JDK 11 and newer versions support TLS 1.3. Also, pooling profile is not compatible with `EofProtocol`.
FieldTypeDescriptionDefault ValueRequired

Rethrow Exception On Read

Boolean

Indicates if the exception should be rethrown if there is a failure while reading

false

### Custom Class Loading Length Protocol A length protocol that uses a specific class loader to load objects from streams.
FieldTypeDescriptionDefault ValueRequired

Class Loader

Any

Max Message Length

Number

Indicates the maximum length of the message.

-1

Rethrow Exception On Read

Boolean

Indicates if the exception should be rethrown if there is a failure while reading

false

## See Also - [Salesforce Help](https://help.salesforce.com) --- product: Sockets Connector version: 1.2 is-latest-version: true --- # Sockets Connector XML and Maven Support > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Although you can manually code a Mule app in XML, it is more efficient to use Anypoint Studio. If you manually code a Mule runtime engine (Mule) app in XML, either from the Anypoint Studio XML editor or from a text editor, you can get access to the connector in your app by adding reference statements to both your XML Mule flow and the Apache Maven `pom.xml` file. When you install the connector in Studio, Studio automatically populates the XML code with the connector’s namespace and schema location. It also adds a dependency to the `pom.xml` file. ## Add a Namespace for the Connector Paste the following code inside the `` tag of the header of your configuration XML: ```xml http://www.mulesoft.org/schema/mule/sockets http://www.mulesoft.org/schema/mule/sockets/current/mule-sockets.xsd ``` This example shows how the namespace statements are placed in the `` XML block: ```xml ``` ## Add a POM File Dependency The Apache Maven `pom.xml` file generated by Anypoint Studio contains dependencies for a Mule app. If you code a Mule app manually, include this XML snippet in your `pom.xml` file to enable access to this connector: ```xml org.mule.connectors mule-sockets-connector x.x.x mule-plugin ``` Replace `x.x.x` with the version that corresponds to the connector you are using. To obtain the most up-to-date `pom.xml` file information: 1. Go to [Anypoint Exchange](https://www.mulesoft.com/exchange/). 2. In Exchange, click **Login** and supply your Anypoint Platform username and password. 3. In Exchange, search for `Sockets`. 4. Select the connector. 5. Click **Dependency Snippets** near the upper right of the screen. ## Next Step After completing your namespace and `pom.xml` file, you can try the [Examples](https://docs.mulesoft.com/sockets-connector/latest/sockets-connector-examples). ## See Also - [Introduction to Anypoint Connectors](https://docs.mulesoft.com/connectors/introduction/introduction-to-anypoint-connectors) - [Salesforce Help](https://help.salesforce.com) --- product: Sockets Connector version: 1.2 is-latest-version: true --- # Sockets Examples > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Anypoint Connector for Sockets (Sockets Connector) enables you to send or receive transport layer packages through both UDP and TCP sockets. The following examples show you how to use the available operations while taking into consideration the transport layer protocol you want to implement in your application, and how to create a custom TPC protocol ## Send a Message In the following example, you have set up your Socket Listener and you want to build an application that upon receiving specific data from an external client, performs a database query and sends a message to a UDP Server Socket with the obtained results. Note that, even though we chose UDP for this example, you can use the Send operation to send messages to both TCP and UDP sockets: ```xml #["SELECT first_name, last_name from SYSTEM.MUSICIANS where id = :id"] ``` To test this example: 1. Initialize an Oracle database by using the following script: ```xml CREATE TABLE SYSTEM.MUSICIANS( id INTEGER GENERATED BY DEFAULT AS IDENTITY, age INTEGER, first_name VARCHAR2(100), last_name VARCHAR2(100), PRIMARY KEY(id) ); INSERT INTO SYSTEM.MUSICIANS(age, first_name, last_name) VALUES(37, 'Farrokh', 'Bulsara'); INSERT INTO SYSTEM.MUSICIANS(age, first_name, last_name) VALUES(36, 'Brian Harold', 'May'); INSERT INTO SYSTEM.MUSICIANS(age, first_name, last_name) VALUES(35, 'Roger', 'Meddows Taylor'); INSERT INTO SYSTEM.MUSICIANS(age, first_name, last_name) VALUES(32, 'John', 'Deacon'); ``` 2. At port 8085, start a UDP server to which the results will be sent by running the netcat command `nc -ul 8085`. 3. Run your Mule application and start a TCP client socket to send the expected query parameter by running netcat command `nc localhost 8082` and sending the data `{"id": 2}`. ## Send and Receive Messages Because sockets are full-duplex, they allow bidirectional communication, enabling you to send and receive messages simultaneously. The following example operation is slightly different from the example of only sending a message because this example not only sends data to the client but also expects a response. This operation can be used for both TCP and UDP sockets. The operation will: 1. Send the data using the client associated to the RequesterConnection. 2. Block until data is received or Timeout is met (in which case a null payload will be returned). Building on the example of only sending data, in this scenario you add a new flow, `socketSendQueryAndReceiveResult`, that connects to the Listener from the `socketSearchDatabaseAndReturnResult` flow, send the query string, and wait for the response, which is then written to a file: ```xml #["SELECT first_name, last_name from SYSTEM.MUSICIANS where id = :id"] ``` To test this example, use the same database setup as used for the sending example, run the Mule application, access the endpoint using the following netcat command `nc localhost 8085`, and send the data `{"id":2}`. ## Create a Custom TCP Protocol The following example creates a TCP-based custom protocol that appends a string header to every message sent and limits input message size to a fixed length by truncating all additional characters. 1. Create a class that implements the `TcpProtocol` interface: ```java package org.mule.extension.socket.protocol; import static java.lang.System.arraycopy; import static org.slf4j.LoggerFactory.getLogger; import org.apache.commons.io.output.ByteArrayOutputStream; import org.mule.extension.socket.api.socket.tcp.TcpProtocol; import org.slf4j.Logger; import java.io.IOException; import java.io.OutputStream; import java.io.InputStream; import java.io.ByteArrayInputStream; import java.io.BufferedOutputStream; public class CustomTestTcpProtocol implements TcpProtocol { protected static final int READ_ATTEMPTS = 50; protected static final int CUSTOM_BUFFER_SIZE = 30; private static final String HEADER = "This is my custom protocol."; private static final Logger LOGGER = getLogger(CustomTestTcpProtocol.class); protected int bufferSize; public CustomTestTcpProtocol() { this(CUSTOM_BUFFER_SIZE); } public CustomTestTcpProtocol(int bufferSize) { this.bufferSize = bufferSize; } @Override public InputStream read(InputStream socketIs) throws IOException { byte[] buffer = new byte[HEADER.length() + bufferSize]; int bytesRead, attempts = 0; while ((bytesRead = socketIs.read(buffer)) <= 0 && (attempts < READ_ATTEMPTS)) { attempts++; } if (bytesRead <= 0) { throw new IOException("Number of read attempts exceeded! Failed to read any data from socket!"); } ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(bytesRead); byteArrayOutputStream.write(buffer, 0, bytesRead); return new ByteArrayInputStream(byteArrayOutputStream.toByteArray()); } @Override public void write(OutputStream os, InputStream data) throws IOException { byte[] messageToSend = new byte[HEADER.length() + bufferSize]; byte[] inputPayload = new byte[bufferSize]; int dataLength = data.read(inputPayload); if (dataLength == bufferSize) { LOGGER.warn("Data length exceeds buffer size so data will be chunked."); } arraycopy(HEADER.getBytes(), 0, messageToSend, 0, HEADER.length()); if (dataLength >= 0) { arraycopy(inputPayload, 0, messageToSend, HEADER.length(), dataLength); } BufferedOutputStream writer = new BufferedOutputStream(os); writer.write(messageToSend, 0, HEADER.length() + dataLength); writer.flush(); } } } ``` 2. Add the class name in the **Connector configuration** window of the Sockets Listener source and either the Sockets Send operation or Send and receive operation: - Sockets Listener source 1. In Studio, open the **Global Element Properties** configuration for your Sockets Listener source. 2. On the **General** tab, set **Protocol** to `Custom protocol`. 3. Add the class name in the **Protocol Class Name** field. ![Sockets Custom Protocol Configuration](/mulesoft/current/en-us/sockets-connector/latest/_images/socket-custom1-configuration.png) Figure 1. Sockets Listener Custom Protocol Configuration - Sockets Send operation or Send and receive operation 1. In Studio, open the **Global Element Properties** configuration of your Sockets Send operation or Send and receive operation. 2. On the **Connection** tab, set **Protocol** to `Custom protocol`. 3. Add the class name in the **Protocol Class Name** field. ![Sockets Send and Receive Custom Protocol Configuration](/mulesoft/current/en-us/sockets-connector/latest/_images/socket-custom2-configuration.png) Figure 2. Sockets Send and Receive Custom Protocol Configuration In the **Configuration XML** tab, use the `class` parameter to add the class in the `sockets:custom-protocol` section of the connector operation: ```xml ``` ## See Also [Introduction to Anypoint Connectors](https://docs.mulesoft.com/connectors/introduction/introduction-to-anypoint-connectors) [Salesforce Help](https://help.salesforce.com) --- product: Sockets Connector version: 1.2 is-latest-version: true --- # Troubleshooting Sockets Connector > For the full documentation index, see: https://docs.mulesoft.com/llms.txt To troubleshoot Anypoint Connector for Sockets (Sockets Connector), become familiar with the information about enabling verbose logging and interpreting commonly thrown messages. ## Enable Verbose Logging To get a better understanding of why an application’s interaction with the Sockets Connector is failing, temporarily enable verbose logging for the connector. Remember to always disable the enhanced verbosity after troubleshooting, because it affects your Mule application performance. To enable verbose logging in the configuration file: 1. Access Anypoint Studio and navigate to the **Package Explorer** view. 2. Open your application’s project name. 3. Open the `src/main/resources` path folder. 4. Open the `log4j2.xml` file inside the folder. 5. Add an `` tag inside the `` tag: ```xml ... ... ``` 6. Save your application changes. 7. Click the project name in **Package Explorer** and then click **Run** > **Run As** > **Mule Application**. ## Understand Common Throws Here is a list of common throw messages and how to interpret them: - SOCKETS:UNKNOWN\_HOST Mule cannot determine the IP address of a host. - SOCKETS:CONNECTIVITY The connection is no longer valid. Apply a reconnection policy if defined in the application setup. - SOCKETS:CONNECTION\_TIMEOUT The attempt to connect to the Socket timed out. - SOCKETS:RETRY\_EXHAUSTED The maximum number of retries for the operation is reached. - SOCKETS:LENGTH\_EXCEEDED There was an attempt of reading or writing more bytes than the allowed limit. ## See Also - [Sockets Connector Reference](https://docs.mulesoft.com/sockets-connector/latest/sockets-documentation) - [Salesforce Help](https://help.salesforce.com) - [Known Issues](https://help.salesforce.com/s/issues) --- product: Sockets Connector version: 1.2 is-latest-version: true --- # Using Anypoint Studio to Configure Sockets Connector 1.2 > For the full documentation index, see: https://docs.mulesoft.com/llms.txt Anypoint Studio (Studio) editors help you design and update your Mule applications, properties, and configuration files. To add and configure a connector in Studio: 1. [Create a Mule project](#create-mule-project). 2. [Add the connector to your Mule project](#add-connector-to-project). 3. [Configure the Sockets Listener source for the connector’s flow](#configure-input-source). 4. [Configure the Send and Receive operations in the flow](#add-connector-operation). 5. [Configure supported TCP protocols](#configure-other-fields). If you are new to configuring connectors in Studio, see [Using Anypoint Studio to Configure a Connector](https://docs.mulesoft.com/connectors/introduction/intro-config-use-studio). If, after reading this topic, you need additional information about the connector fields, see the [Sockets Connector Reference](https://docs.mulesoft.com/sockets-connector/latest/sockets-documentation). ## Create a Mule Project In Studio, create a new Mule project in which to add and configure the connector: 1. In Studio, select **File > New > Mule Project**. 2. Enter a name for your Mule project and click **Finish**. ## Add the Connector to Your Mule Project Add Anypoint Connector for Sockets (Sockets Connector) to your Mule project to automatically populate the XML code with the connector’s namespace and schema location and add the required dependencies to the project’s `pom.xml` file: 1. In the **Mule Palette** view, click **(X) Search in Exchange**. 2. In the **Add Dependencies to Project** view, type `sockets` in the search field. 3. Click **Sockets** in **Available modules**. 4. Click **Add**. 5. Click **Finish**. Adding a connector to a Mule project in Studio does not make that connector available to other projects in your Studio workspace. ## Configure the Sockets Listener Source A source initiates a flow when a specified condition is met. The Sockets Listener source represents a socket endpoint to which clients can connect. By browsing to this endpoint, external clients establish a TCP or UDP socket connection and trigger the flow each time they send a message: 1. In the **Mule Palette** view, select **Sockets** > **Listener**. 2. Drag **Listener** to the Studio canvas. 3. On the **Listener** configuration screen, optionally change the value of the **Display Name** field. 4. Click the plus sign (+) next to the **Connector configuration** field to configure a global element that can be used by all instances of `sockets listener` in the app. 5. On the **General** tab, for **Connection** select the `Tcp listener` or the `Udp listener` connections. 6. Configure the specific tabs for the selected connection:
Tab NameDescription

General

Set the required Host and Port attributes and configure any other optional fields.

Buffer Configuration

Optionally specify send and receive buffer size information.

TLS

Optionally specify the TLS information.

Timeout Configuration

Optionally specify the client and server timeout information.

Advanced

Optionally specify the reconnection information, including a reconnection strategy.

7. Click **Test Connection** to confirm that Mule can connect with the specific server. 8. Click **OK**. In Studio, the Sockets Listener source in the flow looks like this: ![Sockets Listener Source](/mulesoft/current/en-us/sockets-connector/latest/_images/socket-listener-source.png) Figure 1. Sockets Listener Source In Studio, configuring the Sockets Listener source with a TCP connection to accept local incoming connections on port `8082` looks like this: ![Sockets Listener Source Configuration](/mulesoft/current/en-us/sockets-connector/latest/_images/socket-listener-configuration.png) Figure 2. Sockets Listener Source Configuration In the **Configuration XML** tab, the XML looks like this: ```xml ``` ## Configure the Send Operation and the Send and Receive Operation When you add a connector operation to your flow, you immediately define a specific operation for that connector to perform. Sockets Connector provides two basic operations: - Send Sends the data using the client associated to the RequesterConnection - Send and receive Sends the data using the associated client and then blocks until a response is received or the timeout is met, in which case the operation returns a null payload To configure the Send operation or the Send and Receive operation: 1. In the **Mule Palette** view, select either: - **Sockets** > **Send** - **Sockets** > **Send and receive**. 2. Drag the **Send** or the **Send and receive** operation to the Studio canvas. 3. On the operation configuration screen, optionally change the value of the **Display Name** field. 4. Click the plus sign (+) next to the **Connector configuration** field to configure a global element that can be used by all instances of `Sockets Send` or `Sockets Send and receive` in the app. 5. On the **General** tab, for **Connection** select the `Tcp requester` or the `Udp requester` connections. 6. Configure the specific tabs for the selected connection:
Tab NameDescription

General

Set the required Host and Port attributes and configure optional fields as required.

Buffer Configuration

Optionally specify send and receive buffer size information.

Connection

Optionally select and configure one of the supported TCP protocols.

Local Address Settings

Optionally specify the local address.

TLS

Optionally specify the TLS information.

Timeout Configuration

Optionally specify the client and server timeout information.

Advanced

Optionally specify the reconnection information, including a reconnection strategy.

7. Click **Test Connection** to confirm that Mule can connect with the specific server. 8. Click **OK**. Additionally, for the **Send and receive** operation, configure the MIME type as follows: 1. Click the **Send and receive** operation from your flow. 2. On the **MIME Type** tab, select a MIME type from field menu. In Studio, the Sockets Send operation and Send and receive operation in the flow look like this: ![Sockets Send operation Send and Receive operation](/mulesoft/current/en-us/sockets-connector/latest/_images/socket-send-operation.png) Figure 3. Sockets Send operation Send and Receive operation In Studio, configuring either the Send operation or the Send and receive operation with a TCP connection to accept local incoming connections on port `8082` looks like this: ![Sockets Send operation or Send and Receive operation configuration](/mulesoft/current/en-us/sockets-connector/latest/_images/socket-sendreceive-configuration.png) Figure 4. Sockets Send operation or Send and Receive operation configuration In the **Configuration XML** tab, the Send operation configuration XML looks like this: ```xml ``` In Studio, configuring the MIME type as `application/json` for the Send and receive operation looks like this: ![Sockets MIME type Configuration](/mulesoft/current/en-us/sockets-connector/latest/_images/socket-mimetype-configuration.png) Figure 5. Sockets MIME Type Configuration In the **Configuration XML** tab, the Send and receive operation configuration XML looks like this: ```xml ``` ## Configure the Supported TCP Protocols Sockets Connector supports application-level protocols implemented on top of TCP. You must implement these protocols in both client and server ends so they can work properly. By default, the Sockets Connector implements the Safe Protocol; however, you can configure a different protocol for the connector operations both in Anypoint Studio and XML. Supported TCP protocols include the following: - Direct Protocol The socket reads until no more bytes are immediately available. On slow networks, `EOFProtocol` and `LengthProtocol` might be more reliable. - EOF Protocol Reading is terminated by the stream being closed by the client. - Length Protocol This protocol is defined by sending or reading an integer (the packet length) and then the data to transfer. - Custom Class Loading Length Protocol A length protocol that uses a specific class loader to load objects from streams. - Safe Protocol A test protocol that precedes every message with a cookie and which should not be used in production environments. - Streaming Protocol Allows the socket’s Send operation to return a message with the original `InputStream` as payload. - XML Message Protocol Use this protocol to read streaming XML documents. The only requirement is that each document includes an XML declaration at the beginning of the document in the form of ` ``` ### Configure TCP Protocols for Send and Receive Operations To configure supported TCP protocols for either the Send operation or the Send and receive operation: 1. Open the **Global Element Properties** configuration of your Sockets operation. 2. On the **General** tab, for **Connection** select `Tcp requester`. 3. On the **Connection** tab, for **Protocol** select one of the supported protocols. 4. Set the required fields for the connector. 5. Click **Test Connection** to confirm that Mule can connect with the specific server. 6. Click **OK**. In Studio, configuring the Send operation to use Direct Protocol looks like this: ![Sockets Direct Protocol Configuration](/mulesoft/current/en-us/sockets-connector/latest/_images/socket-tcp2-configuration.png) Figure 7. Sockets Direct Protocol Configuration In the **Configuration XML** tab, the XML looks like this: ```xml ``` ## View the App Log To check for problems, you can view the app log: - If you’re running the app from Anypoint Platform, the output is visible in the Anypoint Studio console window. - If you’re running the app using Mule from the command line, the app log is visible in your OS console. Unless the log file path is customized in the app’s log file (`log4j2.xml`), you can also view the app log in the default location `MULE_HOME/logs/.log`. ## See Also - [Introduction to Anypoint Connectors](https://docs.mulesoft.com/connectors/introduction/introduction-to-anypoint-connectors) - [Using Anypoint Studio to Configure a Connector](https://docs.mulesoft.com/connectors/introduction/intro-config-use-studio) - [Sockets Connector Reference](https://docs.mulesoft.com/sockets-connector/latest/sockets-documentation) - [Salesforce Help](https://help.salesforce.com)