doghappy / socket.io-client-csharp

socket.io-client implemention for .NET
MIT License
729 stars 125 forks source link

Await not working in EmitAsync function #251

Open SachinTichkule opened 2 years ago

SachinTichkule commented 2 years ago

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.
doghappy commented 2 years ago

Can you show the relevant server code?

ghost commented 2 years ago

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
    }
BianYuan1995 commented 2 years ago

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

AshotN commented 1 year ago

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

JesseKPhillips commented 1 year ago

My approach to this was to utilize:

TaskCompletionSource<SocketIOResponse> response = new();
... EmitAsync( , response.SetResult);
await response.Task;
64jcl commented 8 months ago

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.