I am trying to send bytes with async version of tcpClient method "SendAsync" but it's not working. Got mistake "Argument type 'byte[]' is not assignable to parameter type 'System.Net.Sockets.SocketAsyncEventArgs'"
. Not async version is working, but can't understand what is wrong with async version. Code below:
IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888);
using Socket tcpListener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
try
{
tcpListener.Bind(endPoint);
tcpListener.Listen();
Console.WriteLine("Server is currently run, waiting for incoming connections");
while (true)
{
using var tcpClient = await tcpListener.AcceptAsync();
var data = MessagePackSerializer.Serialize(DateTime.Now.ToLongTimeString());
await tcpClient.SendAsync(data);
Console.WriteLine($"Client: {tcpClient.RemoteEndPoint} received their data");
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
CodePudding user response:
As noted in the comment, your code is trying to call an overload that doesn't exist. await tcpClient.SendAsync(data, CancellationToken.None);
should work.
Furthermore, I suggest that you re-examine your business requirements. Do you really have to use TCP/IP sockets? TCP/IP socket programming is extremely difficult to do correctly. I strongly recommend using a technology like WebSockets or HTTP instead.