Skip to main content

Client Examples

This section provides instructions for configuring client applications to connect to FreeSWITCH using the Event Socket Library (ESL).

It includes examples for Java and Node.js to demonstrate how to establish a connection, authenticate, and interact with FreeSWITCH.

For more detailed ESL guide, please follow Event Socket Library official docs.

warning

Make sure your FreeSWITCH server is up and running. You should have the Event Socket Interface (ESI) enabled and configured.

Java Example

Dependencies

To use ESL in a Java application, you can use the freeswitch-esl library. Ensure you include it in your project dependencies.

<dependency>
<groupId>org.freeswitch.esl.client</groupId>
<artifactId>org.freeswitch.esl.client</artifactId>
<version>0.9.2</version>
</dependency>

This library is outdated and has not been maintained for some time. Instead, please use the third-party ESL client library below, which supports modern APIs and offers up-to-date dependencies for ESL with Java.

<!-- https://mvnrepository.com/artifact/link.thingscloud/freeswitch-esl-spring-boot-starter -->
<dependency>
<groupId>link.thingscloud</groupId>
<artifactId>freeswitch-esl-spring-boot-starter</artifactId>
<version>x.y.z</version>
</dependency>

To help you get started with using the FreeSWITCH ESL (Event Socket Library) in Java, here are some valuable resources:

These resources should provide you with a solid foundation for working with FreeSWITCH ESL in a Java environment.

Alternatively, you can compile the ESL library from the FreeSWITCH source code by following the ESL compilation guide.

// Be sure to include the esl.jar in your project
import org.freeswitch.esl.*;


public class MyESLTest {

public static void main(final String[] args) {

/*
*
* Once you get libesljni.so compiled you can either put it in your java library path and
* use System.loadlibrary or just use System.load with the absolute path.
*
*/
System.load("/lib64/fs/libesljni.so");

final ESLconnection con = new ESLconnection("127.0.0.1","8021","ClueCon");

if (con.connected() == 1) {
System.out.println("connected");
}

con.events("plain","all");

// Loop while connected to the socket
while (con.connected() == 1) {
final ESLevent eslEvent = con.recvEvent();

// Print the entire event in key : value format.
// serialize() according to the wiki usually takes no arguments
// but if you do not put in something you will not get any output so I just stuck plain in.
System.out.println(event.serialize("plain"));
}
}

}

Node.JS Example

Dependencies

For Node.js, you can use the esl library. Install it using npm:

npm i esl

This module is a promise-based client ('inbound' event socket) and server ('outbound' event socket) for FreeSwitch, written entirely in Javascript with no dependencies on the libesl library.

Code Example

import { FreeSwitchResponse, FreeSwitchServer } from "esl";
import { handleCall } from "./fs_call_handler.js";
import { getLogger } from "../logger/logger.js";
import { fileURLToPath } from "url";
import { basename } from "path";

const logger = getLogger(basename(fileURLToPath(import.meta.url)));

const server: FreeSwitchServer = new FreeSwitchServer({
all_events: true,
my_events: true,
logger: {
info: (msg: string, data: unknown) => {
if (logger.isDebugEnabled()) {
logger.debug(`${msg} ${data}`);
}
},
debug: (msg: string, data: unknown) => {
if (logger.isDebugEnabled()) {
logger.debug(`${msg} ${data}`);
}
},
error: () => {},
},
});

const startFreeSwitchServer = (port: number): FreeSwitchServer => {
logger.info(`Starting FreeSwitch Listener Server on port: ${port}`);

server
.listen({
port: port,
host: "127.0.0.1",
})
.then(() => {
logger.info(`Freeswitch server listening on port: ${port}`);
});

return server;
};

server.on("connection", (call: FreeSwitchResponse) => {
// handle call accordingly
});

const serverPort = 1234;

startFreeSwitchServer(serverPort);

The complete code for this can be found here.

Python Example

Prerequisites

  • FreeSWITCH installed and running on your server.
  • Python ESL library compiled and installed as per previous instructions.
  • Basic knowledge of Python and FreeSWITCH.

Setup

  • Install Python ESL Library: Confirm that the Python ESL library is correctly installed and accessible. You can check this by running:

    python3 -c "import ESL"

Code Example

Here’s a simple Python script that connects to the FreeSWITCH server, sends an API command, and prints the response:

import ESL

# Configuration: Update these variables with your FreeSWITCH server details
hostname = 'localhost' # FreeSWITCH server hostname or IP address
port = 8021 # FreeSWITCH Event Socket port (default is 8021)
password = 'ClueCon' # FreeSWITCH Event Socket password (default is 'ClueCon')

def main():
# Create a new ESL connection
conn = ESL.ESLconnection(hostname, port, password)

# Check if the connection is successful
if not conn.connected():
print("Failed to connect to FreeSWITCH.")
return

print("Connected to FreeSWITCH.")

# Send an API command to FreeSWITCH
response = conn.api("status", "")

# Print the response from FreeSWITCH
print("Response from FreeSWITCH:")
print(response.getBody())

# Clean up and disconnect
conn.disconnect()

if __name__ == "__main__":
main()

Sample output

root@ip-172-31-10-139:/tmp# python3 py_esl.py
Connected to FreeSWITCH.
Response from FreeSWITCH:
UP 0 years, 3 days, 1 hour, 50 minutes, 34 seconds, 255 milliseconds, 170 microseconds
FreeSWITCH (Version 1.10.12 -release 64bit) is ready
89 session(s) since startup
0 session(s) - peak 3, last 5min 0
0 session(s) per Sec out of max 30, peak 2, last 5min 0
1000 session(s) max
min idle cpu 0.00/99.30
Current Stack Size/Max 240K/8192K

Explanation of the Code:

  • Import the ESL Library:

    import ESL

    This imports the compiled ESL library so you can use it in your script.

  • Configuration:

    hostname = 'localhost'
    port = 8021
    password = 'ClueCon'

    Update these values according to your FreeSWITCH server configuration.

  • Create an ESL Connection:

    conn = ESL.ESLconnection(hostname, port, password)

    This establishes a connection to your FreeSWITCH server.

  • Check Connection Status:

    if not conn.connected():
    print("Failed to connect to FreeSWITCH.")
    return

    This checks if the connection was successful.

  • Send an API Command:

    response = conn.api("status", "")

    This sends the status command to FreeSWITCH and stores the response.

  • Print the Response:

    print("Response from FreeSWITCH:")
    print(response.getBody())

    This prints the response from FreeSWITCH to the console.

  • Disconnect:

    conn.disconnect()

    This disconnects from the FreeSWITCH server.

This example provides a basic introduction to interacting with FreeSWITCH using the Python ESL library. You can build upon this example to create more complex applications, such as managing calls or retrieving detailed system information.

Feel free to experiment with different API commands and explore the extensive capabilities of the Event Socket Library!