-
Notifications
You must be signed in to change notification settings - Fork 0
/
TCPClient.cs
67 lines (55 loc) · 1.69 KB
/
TCPClient.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
using System;
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.Runtime.CompilerServices;
public class TCPClient
{
private TcpClient client;
private NetworkStream stream;
public class TCPStreamState
{
public NetworkStream WorkStream;
public byte[] RecvBytes = new byte[1048576];
public TCPStreamState(NetworkStream workStream)
{
WorkStream = workStream;
}
}
public TCPClient(string ipAddress, int port, AsyncCallback connectionHandler)
{
client = new TcpClient();
//Debug.Log("lool");
client.BeginConnect(ipAddress, port, connectionHandler, client);
//Debug.Log("begin");
}
private byte[] AppendLengthByte(byte[] origin)
{
int i = 0;
byte[] length = BitConverter.GetBytes(origin.Length);
length = Support.bytesReverse(length);
byte[] extended = new byte[origin.Length + sizeof(int)];
for (i = 0; i < sizeof(int); i++)
{
extended[i] = length[i];
}
for (; i < origin.Length + sizeof(int); i++)
{
extended[i] = origin[i - sizeof(int)];
}
return extended;
}
public void Send(byte[] data, AsyncCallback sentCallback)
{
stream = client.GetStream();
data = AppendLengthByte(data);
stream.BeginWrite(data, 0, data.Length, sentCallback, stream);
}
public void Read (AsyncCallback readCallback)
{
stream = client.GetStream();
TCPStreamState state = new TCPStreamState(stream);
stream.BeginRead
(state.RecvBytes, 0, state.RecvBytes.Length, readCallback, state);
}
}