(client) chore:Make TCP client async
This commit is contained in:
@ -1,6 +1,7 @@
|
||||
using System;
|
||||
using System.Net.Sockets;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using UnityEngine;
|
||||
using Utils;
|
||||
|
||||
@ -17,7 +18,7 @@ namespace Network
|
||||
/// <param name="address">服务器地址</param>
|
||||
/// <param name="port">端口号</param>
|
||||
/// <returns>连接是否成功</returns>
|
||||
public bool Connect(string address, int port)
|
||||
public async Task<bool> Connect(string address, int port)
|
||||
{
|
||||
if (IsConnected)
|
||||
{
|
||||
@ -31,7 +32,7 @@ namespace Network
|
||||
_tcpClient = new TcpClient();
|
||||
|
||||
// 尝试连接到指定的地址和端口
|
||||
_tcpClient.Connect(address, port);
|
||||
await _tcpClient.ConnectAsync(address, port);
|
||||
|
||||
// 如果连接成功
|
||||
if (IsConnected)
|
||||
@ -82,7 +83,7 @@ namespace Network
|
||||
/// 发送数据到服务器
|
||||
/// </summary>
|
||||
/// <param name="message">要发送的消息</param>
|
||||
public void Send(string message)
|
||||
public async Task Send(string message)
|
||||
{
|
||||
if (!IsConnected)
|
||||
{
|
||||
@ -99,7 +100,7 @@ namespace Network
|
||||
var data = Encoding.UTF8.GetBytes(message);
|
||||
|
||||
// 发送数据
|
||||
stream.Write(data, 0, data.Length);
|
||||
await stream.WriteAsync(data, 0, data.Length);
|
||||
|
||||
Debug.Log($"Sent message to server: {message}");
|
||||
}
|
||||
@ -113,7 +114,7 @@ namespace Network
|
||||
/// 接收来自服务器的数据
|
||||
/// </summary>
|
||||
/// <returns>接收到的消息</returns>
|
||||
public string Receive()
|
||||
public async Task<string> Receive()
|
||||
{
|
||||
if (!IsConnected)
|
||||
{
|
||||
@ -131,7 +132,7 @@ namespace Network
|
||||
{
|
||||
// 读取数据
|
||||
var buffer = new byte[1024];
|
||||
var bytesRead = stream.Read(buffer, 0, buffer.Length);
|
||||
var bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length);
|
||||
|
||||
// 将字节数组转换为字符串
|
||||
var message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
|
||||
|
Reference in New Issue
Block a user