-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnetTcpClient.cs
108 lines (95 loc) · 2.35 KB
/
netTcpClient.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
using UnityEngine;
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
public class TcpClientExample : MonoBehaviour
{
private TcpClient client;
private NetworkStream stream;
private byte[] receiveBuffer = new byte[1024];
private bool isConnected = false;
List<string> getedServerData = new List<string>();
private string ip;
private int port;
private TcpClientExample(string ip,int port=1025)
{
this.ip = ip;
this.port = port;
}
public string GetData():
{
return getedServerData
}
private async void Start()
{
await ConnectToServerAsync(ip, port);
}
private async Task ConnectToServerAsync(string serverIP, int serverPort,string personData)
{
while (!isConnected)
{
try
{
client = new TcpClient();
await client.ConnectAsync(serverIP, serverPort);
stream = client.GetStream();
isConnected = true;
Debug.Log("Ïîäêëþ÷åíî ê ñåðâåðó: " + serverIP + ":" + serverPort);
// Îòïðàâêà äàííûõ íà ñåðâåð
byte[] sendData = Encoding.ASCII.GetBytes(personData);
await stream.WriteAsync(sendData, 0, sendData.Length);
// Ïîëó÷åíèå èíñòðóêöèé îò ñåðâåðà
await ReceiveInstructionsAsync();
}
catch (Exception e)
{
Debug.Log("Îøèáêà ïîäêëþ÷åíèÿ ê ñåðâåðó: " + e.Message);
await Task.Delay(1000); // Ïàóçà ïåðåä ïîâòîðíîé ïîïûòêîé ïîäêëþ÷åíèÿ
}
}
}
private async Task ReceiveInstructionsAsync()
{
try
{
while (isConnected)
{
int bytesRead = await stream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length);
if (bytesRead > 0)
{
// Îáðàáîòêà ïîëó÷åííûõ èíñòðóêöèé
string receivedData = Encoding.ASCII.GetString(receiveBuffer, 0, bytesRead);
getedServerData.Add(receivedData);
Debug.Log("Ïîëó÷åíî îò ñåðâåðà: " + receivedData);
// Ïðîäîëæàåì ïîëó÷àòü äàííûå îò ñåðâåðà
Array.Clear(receiveBuffer, 0, receiveBuffer.Length);
}
else
{
// Çàêðûòèå ñîåäèíåíèÿ ïðè ïîëó÷åíèè ïóñòîãî ñîîáùåíèÿ îò ñåðâåðà
CloseConnection();
}
}
}
catch (Exception e)
{
Debug.Log("Îøèáêà ïðè ÷òåíèè äàííûõ îò ñåðâåðà: " + e.Message);
}
}
private void CloseConnection()
{
try
{
// Çàêðûòèå ñîåäèíåíèÿ
stream.Close();
client.Close();
isConnected = false;
Debug.Log("Ñîåäèíåíèå çàêðûòî");
}
catch (Exception e)
{
Debug.Log("Îøèáêà ïðè çàêðûòèè ñîåäèíåíèÿ: " + e.Message);
}
}
}