NewN_UAVPlane/Assets/Zion/Scripts/Adam/SyncCreateRoom.cs

78 lines
2.1 KiB
C#

// 客户端
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using UnityEngine;
public class SyncCreateRoom
{
public static TcpClient client;
public static NetworkStream stream;
public static string serverReturnValue;
public static async Task StartLinkTCPServer(string serverIp, int serverPort)
{
client = new TcpClient();
await client.ConnectAsync(serverIp, serverPort);
stream = client.GetStream();
await ReciveMessage();
}
public static async void CreateRoom(string roomName)
{
await SendMessageAsync(roomName);
}
public static async Task ReciveMessage()
{
CancellationTokenSource cts = new CancellationTokenSource();
await ReadMessagesAsync(stream, cts.Token);
}
public static async Task SendMessageAsync(string message)
{
if (stream != null)
{
if (!string.IsNullOrEmpty(message))
{
byte[] data = Encoding.UTF8.GetBytes($"{message}: {message}");
await stream.WriteAsync(data, 0, data.Length);
}
}
}
public static async Task ReadMessagesAsync(NetworkStream stream, CancellationToken cancellationToken)
{
byte[] buffer = new byte[1024];
while (!cancellationToken.IsCancellationRequested)
{
try
{
int bytesRead = await stream.ReadAsync(buffer, 0, buffer.Length, cancellationToken);
if (bytesRead > 0)
{
string message = Encoding.UTF8.GetString(buffer, 0, bytesRead);
serverReturnValue = message;
Debug.Log(serverReturnValue);
}
}
catch (OperationCanceledException)
{
// Ignore cancellation exceptions
}
}
}
public static void CloseClint()
{
client.Close();
if (stream != null)
{
stream.Close();
stream.Dispose();
}
}
}