1
|
using System.Collections;
|
2
|
using System.Collections.Generic;
|
3
|
using UnityEngine;
|
4
|
using System.Net.Sockets;
|
5
|
using System.Net;
|
6
|
using System;
|
7
|
|
8
|
public class Client : MonoBehaviour
|
9
|
{
|
10
|
public static Client instance;
|
11
|
public static int dataBufferSize = 4096;
|
12
|
public int port = 26950;
|
13
|
public int myId = 0;
|
14
|
public TCP tcp;
|
15
|
|
16
|
private void Awake()
|
17
|
{
|
18
|
if (instance == null)
|
19
|
{
|
20
|
instance = this;
|
21
|
}
|
22
|
else if (instance != this)
|
23
|
{
|
24
|
Debug.Log("Client instance already exists, destroying object!");
|
25
|
Destroy(this);
|
26
|
}
|
27
|
}
|
28
|
|
29
|
private void Start()
|
30
|
{
|
31
|
tcp = new TCP();
|
32
|
}
|
33
|
|
34
|
public void ConnectToServer(string ip)
|
35
|
{
|
36
|
Debug.Log($"Connecting to {ip}.");
|
37
|
tcp.Connect(ip);
|
38
|
}
|
39
|
|
40
|
public class TCP
|
41
|
{
|
42
|
public TcpClient socket;
|
43
|
public NetworkStream stream;
|
44
|
private byte[] receiveBuffer;
|
45
|
|
46
|
public void Connect(string ip)
|
47
|
{
|
48
|
socket = new TcpClient
|
49
|
{
|
50
|
ReceiveBufferSize = dataBufferSize,
|
51
|
SendBufferSize = dataBufferSize
|
52
|
};
|
53
|
|
54
|
receiveBuffer = new byte[dataBufferSize];
|
55
|
socket.BeginConnect(ip, instance.port, ConnectCallback, socket);
|
56
|
}
|
57
|
|
58
|
private void ConnectCallback(IAsyncResult _result)
|
59
|
{
|
60
|
socket.EndConnect(_result);
|
61
|
|
62
|
if (!socket.Connected)
|
63
|
{
|
64
|
return;
|
65
|
}
|
66
|
|
67
|
stream = socket.GetStream();
|
68
|
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
|
69
|
}
|
70
|
|
71
|
private void ReceiveCallback(IAsyncResult _result)
|
72
|
{
|
73
|
try
|
74
|
{
|
75
|
int _byteLength = stream.EndRead(_result);
|
76
|
if (_byteLength <= 0)
|
77
|
{
|
78
|
// TODO: disconnect
|
79
|
return;
|
80
|
}
|
81
|
|
82
|
byte[] _data = new byte[_byteLength];
|
83
|
Array.Copy(receiveBuffer, _data, _byteLength);
|
84
|
|
85
|
// TODO: handle data
|
86
|
|
87
|
stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
|
88
|
}
|
89
|
catch (Exception _ex)
|
90
|
{
|
91
|
Console.WriteLine($"Error receiving TCP data: {_ex}");
|
92
|
// TODO: Disconnect client
|
93
|
}
|
94
|
}
|
95
|
|
96
|
}
|
97
|
}
|