socket.io-client-csharp icon indicating copy to clipboard operation
socket.io-client-csharp copied to clipboard

Await not working in EmitAsync function

Open SachinTichkule opened this issue 4 years ago • 6 comments

I want to await until response is not got, but its goes further without getting response in emitasync in don't want to use on Method, i working on login and login response i want to wait until login response is not got. Example Code:

        JSONNode keyValuePairs = new JSONObject();
        keyValuePairs.Add("username", userNameInputField.text.Trim());
        keyValuePairs.Add("password", passwordInputField.text.Trim());
        keyValuePairs.Add("platform", "web");
        StringBuilder stringBuilder = null;
        await MySocket.socket.EmitAsync(eventName: SocketEvents.login, ack: (response) =>
        {
            stringBuilder = new StringBuilder(response.ToString());

            // Debug.LogError(response.ToString());
            // string s = response.GetValue<string>();
            // Debug.LogError(s);

            //jsonnode = JSON.Parse(response.GetValue<string>());

        },
           data: keyValuePairs.ToString());

        while (stringBuilder == null)
        {
            await Task.Yield();
        }

        stringBuilder.Remove(0, 1);
        stringBuilder.Remove(stringBuilder.Length - 1, 1);
        jsonnode = JSON.Parse(stringBuilder.ToString());
    I want to remove while loop in my code due to not await its gonna happen. please fix out.
   

SachinTichkule avatar Jan 04 '22 05:01 SachinTichkule

Can you show the relevant server code?

doghappy avatar Jan 05 '22 08:01 doghappy

I have same issue await EmitAsync not wait until response arrived. I'm tried to find a way Wait until response arrived without waiting loop

here's server code typescript

/* eslint-disable @typescript-eslint/no-shadow */
import { Socket, Server } from 'socket.io';

io.on('connection', async (socket: Socket) => {
  log(`connection: ${socket.id}`);

  socket.on('createRoom', async (roomId:string, name:string, callback: (data:any) => any) => {
    let room = rooms.get(roomId);
    if (!room) {
      log('create room cause no room');
      const makeWorkers = await WorkerFactory.init();
      const worker = await makeWorkers.createWorkers();
      room = await Room.create(roomId, worker, io);
      room.addPeer(new Peer(socket.id, name));
      rooms.set(roomId, room);
      streamer.set(socket.id, room);
    } else {
      room.addPeer(new Peer(socket.id, name));
    }
    socket.join(roomId);
    callback(room.roomId);
  });

Also My code

  public async UniTaskVoid CreateRoom_Test(int roomId, string userName = "NULL")
    {
        await ClientSocket.EmitAsync("createRoom", async response =>
        {
            string responseResult = response.ToString();
            responseResult = responseResult.TrimStart('[');
            responseResult = responseResult.TrimEnd(']');
            Debug.Log("[Debug]createRoom response:" + responseResult);
            UserListManager.CurrentRoomNumber.Value = int.Parse(responseResult);

            await AddPeersAsync(roomId);//<- I want to this code at out ack response
        }, roomId, userName).AsUniTask();
       //await AddPeersAsny(roomId) // Like this
    }

ghost avatar May 03 '22 01:05 ghost

I have same issue await EmitAsync not wait until response arrived. socketioClient version 3.0.3

BianYuan1995 avatar May 18 '22 03:05 BianYuan1995

@doghappy is there a way we are supposed to await the returned data?

AshotN avatar Oct 29 '22 22:10 AshotN

My approach to this was to utilize:

TaskCompletionSource<SocketIOResponse> response = new();
... EmitAsync( , response.SetResult);
await response.Task;

JesseKPhillips avatar Sep 01 '23 20:09 JesseKPhillips

I am using SocketIOUnity that is built on top of this library. I am having issues where sending two Emits after each other seems to cause some kind of exception and disconnect from the socket if the first Emit contains some amount of data (mine is about 40000 bytes). It feels like the emit's are actually run concurrently then which causes issues. All the calls in that library lead to these EmitAsync methods so wondering if they could be connected then to this issue.

https://github.com/itisnajim/SocketIOUnity/issues/78

EDIT: As I mention on that thread, I came to the following solution (within an IEnumerable in Unity):

Task t = socket.EmitAsync("mic", byteBuffer);
Dbg.Log("Sent!");
yield return new WaitUntil(() => t.IsCompleted);
// send next socket emit

I have to make a queue and dispatch one at a time then.

64jcl avatar Dec 31 '23 09:12 64jcl