-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUDP.cs
86 lines (75 loc) · 2.79 KB
/
UDP.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
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
// https://gist.github.com/louis-e/888d5031190408775ad130dde353e0fd#file-udpsocket-cs
namespace UDP
{
public class UDPSocket
{
public Socket _socket;
private const int bufSize = 8 * 1024;
private State state = new State();
private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
private AsyncCallback? recv = null;
public class State
{
public byte[] buffer = new byte[bufSize];
}
public void Server(string address, int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
_socket.Bind(new IPEndPoint(IPAddress.Parse(address), port));
Receive();
}
public void Client(string address, int port)
{
_socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
_socket.Connect(IPAddress.Parse(address), port);
Receive();
}
public void Send(string text)
{
byte[] data = Encoding.ASCII.GetBytes(text);
_socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndSend(ar);
Console.WriteLine("SEND: {0}, {1}", bytes, text);
}, state);
}
private void Receive()
{
_socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
{
try
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndReceiveFrom(ar, ref epFrom);
_socket.BeginReceiveFrom(so.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv, so);
Console.WriteLine("RECV: {0}: {1}, {2}", epFrom.ToString(), bytes, Encoding.ASCII.GetString(so.buffer, 0, bytes));
} catch { }
}, state);
}
}
}
namespace UDP
{
class Program
{
static void Main(string[] args)
{
UDPSocket s = new UDPSocket();
s.Server("127.0.0.1", 27000);
UDPSocket c = new UDPSocket();
c.Client("127.0.0.1", 27000);
// c.Send((char));
Console.ReadKey();
s._socket.Close(); //Fixed closing bug (System.ObjectDisposedException)
//Bugfix allows to relaunch server
Console.WriteLine("Closed Server \n Press any key to exit");
Console.ReadKey();
}
}
}