PC-20230316NUNE\Administrator 894100ae37 提交Unity 联机Pro
2024-08-17 14:27:18 +08:00

34 lines
1010 B
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace JNGame.Util
{
public class NetTool
{
public static async Task SendAsync(Socket socket, byte[] buffer)
{
// 注意这里我们实际上并没有直接使用async/await因为BeginSend是回调模式
// 但我们可以使用TaskCompletionSource来桥接回调和async/await
var tcs = new TaskCompletionSource<int>();
// 异步发送数据
socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, (ar) =>
{
try
{
int bytesSent = socket.EndSend(ar);
tcs.SetResult(bytesSent);
}
catch (Exception ex)
{
tcs.SetException(ex);
}
}, null);
// 等待发送完成
await tcs.Task;
}
}
}