-
Notifications
You must be signed in to change notification settings - Fork 0
/
Networking.cs
executable file
·73 lines (62 loc) · 1.93 KB
/
Networking.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
//Networking.cs
//related link
//https://www.youtube.com/watch?v=xx5Xyxrq5Bc
//https://www.youtube.com/watch?v=WwI_tDqKS8Y
//https://forum.unity.com/threads/writing-and-reading-a-socket-with-tcp.282071/
using System.Net.Sockets; //library to use Sockets
using UnityEngine;
using System; //to use Action (callbacks)
using System.Text; //to decode bytes from server
public class Networking : MonoBehaviour
{
TcpClient client = new TcpClient();
NetworkStream stream; //to read and write
const string IP = "192.168.1.40"; //server ip (To be changed)
const int PORT = 3000; //port (To be changed)
const double memory = 5e+6; //means 5mbs en bytes
const int timeTryingConnect = 5000; //time to connect
public byte[] data = new byte[(int)memory]; //where we store data from server
private void Start()
{
conectar((bool res) =>
{
if (res == true)
{
stream = client.GetStream();//getting stream instance
Debug.Log("ok");
}
else
{
Debug.Log("Connection Fail");
}
});
}
private void conectar(Action<bool> callback)
{
bool result = client.ConnectAsync(IP, PORT).Wait(timeTryingConnect);
callback(result);
}
private void Update()
{
if (stream.DataAvailable)
{
receiveMsg();
}
}
void receiveMsg()
{
int size = stream.Read(data, 0, data.Length);
string message = Encoding.UTF8.GetString(data, 0, size);
Debug.Log(message);
}
void sendMsg(string msg)
{
Byte[] sendBytes = Encoding.UTF8.GetBytes(msg);
stream.Write(sendBytes, 0, sendBytes.Length);
}
private void OnApplicationQuit()
{
sendMsg("Closing (Message from CLIENT)");
client.Close();
}
}