# Sockets

**URL:** https://heroiclabs.com/docs/nakama/concepts/sockets/
**Summary:** Sockets are used to establish connections between the server and clients. This allows the server to send data to and receive data from clients, enabling real-time communication and gameplay.
**Keywords:** sockets, nakama
**Categories:** nakama, sockets, concepts

---


# Sockets

Socket connections are used in Nakama to enable real-time communication and gameplay between servers and clients. Clients can establish a socket connection to the server, allowing the server to send data to and receive data from the client, enabling use of the real-time features in Nakama.

There are many different ways that socket connections can be used in Nakama, depending on the specific requirements of the game. Socket connections can be used in Nakama to enable:

* **Tracking online [status](../status/)**: Socket connections can be used to track which clients are online and available for gameplay. This allows you to keep track of which clients are active and which are inactive, and can help you manage resources effectively.
* **Sending and receiving data**: Socket connections are used to send and receive data between the game server and clients. This can include gameplay data, such as player movements and actions, as well as other types of data, such as chat messages and system messages.

Socket connections are a key tool for enabling real-time communication and gameplay in Nakama, and they are used for a variety of features, including [chat](../chat/), [parties](../parties/), [multiplayer](../multiplayer/), and more.

## Socket connection lifecycle

Socket connections are established between the game server and clients, and they are used to send and receive data between the two. The lifecycle of a socket connection is as follows:

1. The client establishes a socket connection
1. The client sends and receives data to and from the server
4. The client disconnects from the server

### Establishing a socket connection

A socket is created from the client object:

{{< code type="client" >}}
```csharp
var socket = client.NewSocket();

bool appearOnline = true;
int connectionTimeout = 30;
await socket.ConnectAsync(Session, appearOnline, connectionTimeout);

// If you want socket handlers to execute outside of the main thread,
// pass 'useMainThread' as false when creating the socket
var socket = client.NewSocket(useMainThread: false);
```
{{< /code >}}

{{< code type="client" >}}
```swift
let socket = client.createSocket() as! Socket

socket.connect(session: session, appearOnline: true)
```
{{< /code >}}

{{< code type="client" >}}
```dart
const host = '127.0.0.1';
const ssl = false;

final socket = NakamaWebsocketClient.init(
  host: 'host',
  ssl: ssl,
  token: session.token,
);

// The socket automatically connects after created
```
{{< /code >}}

{{< code type="client" >}}
```javascript
const socket = client.createSocket();

var appearOnline = true;
await socket.connect(session, appearOnline);
```
{{< /code >}}

{{< code type="client" framework="godot3" >}}
```gdscript
# Make this a node variable or it will disconnect when the function that creates it returns

onready var socket := Nakama.create_socket_from(client)

func _ready():
    var connected : NakamaAsyncResult = yield(socket.connect_async(session), "completed")
    if connected.is_exception():
        print("An error occurred: %s" % connected)
        return
    print("Socket connected.")
```
{{< /code >}}

{{< code type="client" framework="godot4" >}}
```gdscript
# Make this a node variable or it will disconnect when the function that creates it returns

@onready var socket := Nakama.create_socket_from(client)

func _ready():
    var connected : NakamaAsyncResult = await socket.connect_async(session)
    if connected.is_exception():
        print("An error occurred: %s" % connected)
        return
    print("Socket connected.")
```
{{< /code >}}

{{< code type="client" >}}
```cpp
NRtClientPtr rtClient;
rtClient = client->createRtClient();

bool createStatus = true;
rtClient->connect(session, createStatus);
```
{{< /code >}}

{{< code type="client" >}}
```java
SocketClient socket = client.createWebSocket();

SocketListener listener = new AbstractSocketListener() {
    @Override
    public void onDisconnect(final Throwable t) {
        logger.info("Socket disconnected.");
    }
};

socket.connect(session, listener).get();
logger.info("Socket connected.");
```
{{< /code >}}

{{< code type="client" lang="lua" framework="defold" >}}
```lua
local socket = nakama.create_socket(client)

nakama.sync(function()
    -- connect
    local ok, err = nakama.socket_connect(socket)

    if ok then
      -- do socket stuff
    end

    if err then
      print(err.message)
    end
end)
```
{{< /code >}}

{{< missing type="client" lang="bash" / >}}
{{< missing type="client" lang="shell" / >}}

### Sending and receiving data

Once a socket connection has been established, the client can send and receive data to and from the server. This connection is used for all real-time features of Nakama. See specific examples on the pages for these features:

* [Chat](../chat/)
* [Parties](../parties/)
* [Multiplayer](../multiplayer/)
* [Status](../status/)

### Disconnecting from the server

Socket connections are closed when the client disconnects from the server. This can also be done manually by calling the given method on the socket:

{{< code type="client" >}}
```csharp
socket.CloseAsync();
```
{{< /code >}}

{{< code type="client" >}}
```swift
socket.disconnect()
```
{{< /code >}}

{{< code type="client" >}}
```dart
await socket.close();
```
{{< /code >}}

{{< code type="client" >}}
```javascript
socket.disconnect();
```
{{< /code >}}

{{< code type="client" framework="godot3" >}}
```gdscript
socket.close()
print("Socket disconnected.")
```
{{< /code >}}

{{< code type="client" framework="godot4" >}}
```gdscript
socket.close()
print("Socket disconnected.")
```
{{< /code >}}

{{< code type="client" >}}
```cpp
rtClient->disconnect();
```
{{< /code >}}

{{< code type="client" >}}
```java
socket.disconnect().get()
```
{{< /code >}}

{{< code type="client" lang="lua" framework="defold" >}}
```lua
-- Sockets can not be manually closed in Defold
```
{{< /code >}}

{{< missing type="client" lang="bash" / >}}
{{< missing type="client" lang="shell" / >}}

## Socket events

There are a number of events that can be used to monitor the state of a socket connection or events that occur on the socket, which can be used to trigger actions in your game.

The following events are available for socket connections:

{{< table name="nakama.concepts.sockets.events" >}}
