# WebSockets

You can connect to your web socket server to send/receive JSON messages from blueprint.

## Usage Overview

There are two different types of web socket connections

* `M2_JsonWebSocketConnection` - can be used for sending and receiving json messages
* `M2_StringWebSocketConnection` - can be used for sending and receiving string messages
* (`M2_WebSocketConnection` has been deprecated)

To use one of these web socket connections, create a new instance of the class and store it somewhere in a Blueprint graph.

<figure><img src="https://1456550285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoWTlPaoHd1McSakqMigu%2Fuploads%2Fgit-blob-2fe6b7e21ca2cfdd05c7d6ff6f421aecaf289422%2Fimage.png?alt=media" alt=""><figcaption><p>Creating an instance of the json web socket</p></figcaption></figure>

For example usage, please see `BP_WebsocketExample`. This provides a complete example of connecting to, sending and receiving messages using a `M2_JsonWebSocketConnection`.

### Connecting

To connect to the Web Socket server you call the Connect method on the connection class. This is `Connect Json Websocket`, or `Connect String Websocket` respectively.

<figure><img src="https://1456550285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoWTlPaoHd1McSakqMigu%2Fuploads%2Fgit-blob-71cd68e827aa4b03a6bb2b97224cc19eb89f7ba6%2Fimage.png?alt=media" alt=""><figcaption><p>The two "connect" methods. Some of the advanced parameters are collapsed by default</p></figcaption></figure>

The parameters are as follows:

| Parameter           | Description                                                                                                                                                                                                                                                                              | Required            |
| ------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------- |
| Url                 | <p>The web socket URL to connect to. The <code>wss</code> or <code>ws</code> protocols must be specified.</p><p>This URL must conform to the requirements described in <a href="configuring-external-url-access">Configuing External URL Access</a></p>                                  | Yes                 |
| Protocol            | <p>An optional <a href="https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API/Writing_WebSocket_servers#subprotocols">subprotocol </a>to pass to your server on connection.<br><br>If not specified, this will default to empty.</p>                                           | No                  |
| Authentication      | Optional authentication headers, using M2's built-in authentication, used in the same way as Http requests. See [#authentication](https://docs.msquared.io/creation/unreal-development/features-and-tutorials/http-requests#authentication "mention")                                    | No                  |
| Headers             | An optional collection of other headers to pass to your server as part of the handshake. Used in the same way as Http headers. See [#headers](https://docs.msquared.io/creation/unreal-development/features-and-tutorials/http-requests#headers "mention")                               | No                  |
| On Connected        | <p>A delegate that is called if the web socket successfully connects.<br><br>When this event is received, you can send and receive messages.</p>                                                                                                                                         | No, but recommended |
| On Connection Error | <p>A delegate that is called if the web socket fails to connect.<br><br>If this is called, the web socket cannot be used until it is connected.</p>                                                                                                                                      | No, but recommended |
| On Disconnected     | <p>A delegate that is called if the web socket disconnects.<br><br>This is called if the disconnection is user driven or the server connection is broken.<br><br>If this is called, the web socket cannot be used until it is connected.</p>                                             | No, but recommended |
| On Message Received | <p>A delegate that is called whenever the web socket receives a message from the server.<br><br>Messages must be deserializable from a JSON string to be passed to your handler.<br><br>If you do not provide this delegate, your socket will ignore any messages that are received.</p> | No, but recommended |

The outputs are as follows:

| Parameter                     | Description                                                                                                                                                                                                                                                                                     |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Connecting                    | The connection request was correctly sent. From this point, either `OnConnected` or `OnConnectionError` will be called.                                                                                                                                                                         |
| Invalid Url                   | The connection request was not sent because the provided Url was rejected.                                                                                                                                                                                                                      |
| Url Blocked                   | The connection request was not sent, because the Url was not allowed, due to the access policy for your organization. See [configuring-external-url-access](https://docs.msquared.io/creation/unreal-development/features-and-tutorials/web-services/configuring-external-url-access "mention") |
| Invalid Headers               | The connection request was not sent because the provided headers were rejected.                                                                                                                                                                                                                 |
| Failed                        | Failed for a reason not related to the parameters. If this happens, please check your logs for errors.                                                                                                                                                                                          |
| Failed Connection In Progress | The current connect call failed because there was already an existing connection in progress (or the websocket has already connected)                                                                                                                                                           |

### Sending Messages

Once your web socket is connected you can send messages via the appropriate "Send" functions:

* For `M2_JsonWebSocketConnection`, you have `SendJsonObject` and `SendJsonValue`, either of which can be used. These will be sent to your remote server as serialized strings.
* For `M2_StringWebSocketConnection`, you have `SendMessage`

`SendJson`. This will take a `JsonObject` and send it to your remote server as a serialized string.\
\\

<figure><img src="https://1456550285-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoWTlPaoHd1McSakqMigu%2Fuploads%2Fgit-blob-b4b1c9a47dcbc7f6b2b8aa3aa96c52f6be5a03f4%2Fimage.png?alt=media" alt=""><figcaption><p>Sending a "Json Object message" via a <code>M2_JsonWebSocketConnection</code></p></figcaption></figure>

### Handling Disconnection

Disconnection can be manually requested by calling the `Disconnect` event. This will send a default status of `1000` and no reason string.

Your web socket server connection may be disconnected for other means, such as network errors between the client and web socket server, problems in the web socket server or just that the connection is set to time out.

You can call `Reconnect` to connect to a web socket that has moved into the disconnected state; however you must have called `Connect` on it beforehand.

{% hint style="info" %}
Due to the custom nature of many web socket services, we do not provide automatic reconnection logic. You must manage this yourself by calling `Reconnect` if required.
{% endhint %}
