Issue with socket connection

my game suddenly disconnects from socket and i don’t know why.
i’m using unity sdk and before i had some issues with socket time out but then i fixed it with setting my
outgoing_queue_size to 60 any less than that it tells me on going queue size is full.
this is my socket setup

socket:
server_key: “defaultkey”
port: 7350
max_message_size_bytes: 4096
read_timeout_ms: 10000
write_timeout_ms: 10000
idle_timeout_ms: 60000
write_wait_ms: 5000
pong_wait_ms: 10000
ping_period_ms: 8000
outgoing_queue_size: 60

i also checked my internet connection when internet goes down i create another socket and rejoin a match like this:

IEnumerator Reconnect()
{
    yield return new WaitForSeconds(3);

    CreateNewSocket();
}

public async void CreateNewSocket()
{
    if (!isession.IsExpired)
    {
        Debug.Log("reconnected");
        isocket = iclient.NewSocket();
        int connectionTimeout = 30;
        await isocket.ConnectAsync(isession, true, connectionTimeout);
        PassData.isocket = isocket;

        if (isocket.IsConnected || isocket != null)
        {
            await isocket.JoinMatchAsync(PassData.Match.Id);
            ReconnectSocket = true;
            Debug.Log("re joined the match");

            Debug.Log("my id" + PassData.Match.Self.UserId);

            SystemSettings.instance.ConnectionPanel.SetActive(false);
        }


    }
    else
    {
        Debug.Log("session expired");
        isession = await iclient.SessionRefreshAsync(isession);
    }
}

this works fine when i turn off wifi and reconnect
but i still face socket disconnection sometimes, this error shows up when i try to send states
SocketException: The socket is not connected:

Nakama.WebSocketAdapter.SendAsync (System.ArraySegment`1[T] buffer, System.Boolean reliable, System.Threading.CancellationToken canceller) (at :0)

my session expiry is set to 10800 seconds.
and i don’t know if this helps anyone to diagnose this issue with me i have 19 opcodes each sends one or two strings in each state.

is there away to check when socket disconnects??
i used if(! isocket.isconnected) but it does not seem to detect my issue!!!

any help on this is much appreciated

1 Like

Any Updates on this dears?

Hello @sana2024, you should use the socket.OnDisconnected event to handle disconnects.

thank you so much for your reply,
where and when to use that,
i tried it in my code but it seems there is not function like that

in some cases i tried to handle it my self by checking if(socket.isconnected== false) but this does not works the way i want it to.
so every time this disconnect occurs i have to check for disconnect, create new socket, rejoin the match again and asign the new socket to on recive match state???

can you please provide me an example on this?

Apologies, the correct action would be Closed and not OnDisconnected.

You do not need to reassign the OnReceiveMatchState function, but you will need to reuse the socket to reconnect and rejoin the match.

You’d do something like in this test, but instead of the completer fn you’d pass your own with the reconnection logic - using the _socket.ConnectAsync(session) function.

If you’re using authoritative matches you can see this example on how to handle reconnects server side.

As for your original question, having to increase the outgoing_queue_size could indicate that your client isn’t consuming the messages fast enough, either because there are too many of them or because it’s slow to process them.

wow, what a great response, i didn’t know these test cases existed, thank you,
here is what i’ve set my disconnection configuration by myself before and i’m not sure if i did it right so i need someone to review it for me:

i have this case were i check internet connection

if internet connection lose and returned i call a reconnect function

then i check if the session is expired if not i create a new socket, if yes then i refresh the session

and rejoin the match again
but the problem is i have the on receive match state inside start method so i used this inside update function

this is for checking internet disconnection but i wanted something to just directley check socket disconnect.

by the way, my manager decided to fire me if i didn’t fix these problems by the end of week and publish the app so thats why in a bit rush, sorry for any pressure i put on this team,
thank you again, you are very helpfull.

I suggest you take a look at our PiratePanic example game implemented using Unity and server authoritative code in TS: unity-sampleproject/Scene01MainMenuController.cs at master · heroiclabs/unity-sampleproject · GitHub

It only handles reconnection and not rejoining the match, hopefully it can be useful to you as an example you can build upon.

1 Like

okay this might sound mind blowing but socket.closed doesn’t work at all now,
two weeks ago i configurate this as you mentioned like this

	private async void Connect(ISocket socket, ISession session)
	{
		try
		{
			if (!socket.IsConnected)
			{
				await socket.ConnectAsync(session);
			}
		}
		catch (Exception e)
		{
			Debug.LogWarning("Error connecting socket: " + e.Message);
		}
	}
}

this was working like a charm i tested it a thousand times it could handle any dissconnection
i was dissconecting my internet and reconnecting again and the socket was back immediately,
and then i finished my game and publish it, and everyone was complaining about disconnection
and i went back to the code to see what is happenening and it turned out socked closed doesn’t run at all, i havent touched a single line of code, please i want to know what am i doing wrong???

@sana2024 are you using the latest Unity SDK?

I’m using 3.12.

@sana2024 latest Unity SDK would be v3.5.0, so I’m not sure if you mistyped or provided the wrong version. Either way, I’d suggest you upgrade both Nakama and the Unity SDK to latest if possible.

this what i’m using inside my vm , thats what i meant.

The latest Nakama version is 3.14.0. It’s always advisable to be on the latest if possible, however I was suggesting that you upgrade the latest Nakama Unity client SDK if you’re running an outdated version in your clients.

i updated nakama SDK to 3.5.0 just now, thanks for your help.