# Websockets

```lua
function yourEvent(title, type, message, code)
 
    if title ~= socket then --make sure we're using the socket title we want!
        return; --otherwise exit out early :)
    end
    
    if type == 'OnMessage' then
        --route all messages here!
        --the code will be blank. ''
        log('receiving message: ' .. message);
    end
    if type == 'OnOpen' then
        --the socket opened!!
        --the message and code will be blank. ''
        log('socket was opened!');
    end
    
    if type == 'OnClose' or type == 'OnError' then
        --if the message type is OnClose or OnError, let's clean up the socket...
        local app = getApp();
        app.removeWebSocket(socket);
        log('socket is closed!');
        log(message);
        log(code);
    end
end

socket = 'my_socket_title'; --just storing the title in a global variable...
return function()
    local app = getApp();
    
    --remove old existing websocket just incase...
    app.removeWebSocket(socket);
    wait(1); --give it time to remove the old one
    addEvent('websocket', 'yourEvent'); --subscribe to all websockets that exist...
    
    --this wss server will echo whatever you send!
    app.createWebsocket(socket, 'wss://ws.ifelse.io/'); --title a websoscket and connect to a server...
    wait(2); --give it time to connect
    app.sendWebsocketMessage(socket, 'gogo!');
    wait(2);
    log('nice job... we gunna wait until close now!');
    keepAlive();
end
```

{% hint style="info" %}
Events are asynchronous coroutines.
{% endhint %}


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.streamavatars.com/lua-scripting-api/api-reference-and-tips/events/websockets.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
