Server communication via async/await?

前端 未结 2 1121
长情又很酷
长情又很酷 2021-01-27 03:32

I want to create Socket message sending via TAP via async/await.

After reading this answer and this one - I decided to create a fully working sample :

So what ha

2条回答
  •  余生分开走
    2021-01-27 04:09

    since you do not wait for the threads to do their work and then call s.Close() the socket will be closed before any traffic is sent out. You would have to either remove the s.Close() call or wait until the calls are complete, for instance via

     Task connect = s.ConnectTaskAsync( "127.0.0.1" , 443);
     connect.Wait(); // you have to connect before trying to send
     Task sendData = s.SendTaskAsync(Encoding.UTF8.GetBytes("hello"));
     sendData.Wait(); // wait for the data to be sent before calling s.Close()
    
     s.Close();
    

    or you could box it in a method and Wait for that method to complete. The end result is to not call Close before completing the previous calls.

     void Main()
     {
         Socket s = new Socket(SocketType.Stream    , ProtocolType.Tcp);
         Task worker = DoWorkAsync(s);
         worker.Wait();
         s.Close();
         Console.ReadLine();
    }
    
    private async Task DoWorkAsync(Socket s){
         await s.ConnectTaskAsync( "127.0.0.1" , 443);
         await s.SendTaskAsync(Encoding.UTF8.GetBytes("hello"));
    }
    

提交回复
热议问题