-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetClient.cs
More file actions
84 lines (74 loc) · 2.43 KB
/
NetClient.cs
File metadata and controls
84 lines (74 loc) · 2.43 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
namespace NetAzy
{
public class NetClient
{
private Socket socket;
private byte[] receiveBuffer;
public delegate void OnMessageReceivedDel(IncomingNetMessage msg);
public OnMessageReceivedDel OnMessageReceived;
public bool Connect(string str_ip, int port)
{
IPAddress ip = Helper.ResolveAdress(str_ip);
socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
socket.Connect(ip, port);
receiveBuffer = new byte[socket.ReceiveBufferSize];
socket.BeginReceive(receiveBuffer, 0, socket.ReceiveBufferSize, 0, new AsyncCallback(readMessage), null);
return true;
}
private void readMessage(IAsyncResult ar)
{
try
{
// Read data from the client socket.
int read = socket.EndReceive(ar);
// Data was read from the client socket.
if (read > 0)
{
byte[] bytes = new byte[read];
for (int i = 0; i < read; i++)
{
bytes[i] = receiveBuffer[i];
}
IncomingNetMessage msg = new IncomingNetMessage(bytes);
if (OnMessageReceived != null)
OnMessageReceived(msg);
socket.BeginReceive(receiveBuffer, 0, socket.ReceiveBufferSize, 0,
new AsyncCallback(readMessage), null);
}
}
catch (SocketException e)
{
if (e.ErrorCode == 10054)
{
Console.WriteLine("Server shutdown");
}
else
{
throw new Exception("Unkown Error: " + e);
}
}
}
public bool SendMessage(OutgoingNetMessage msg)
{
try
{
socket.BeginSend(msg.Bytes, 0, msg.Size, 0, new AsyncCallback(messageSent), null);
return true;
}
catch(Exception)
{
return false;
}
}
private void messageSent(IAsyncResult ar)
{
socket.EndSend(ar);
}
}
}