-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUDPSocket.cs
More file actions
62 lines (54 loc) · 1.97 KB
/
Copy pathUDPSocket.cs
File metadata and controls
62 lines (54 loc) · 1.97 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
using System;
using System.Net;
using System.Net.Sockets;
using System.Text;
namespace MiLightYL5
{
public class UDPSocket
{
private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private const int bufSize = 64;
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.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.ReuseAddress, true);
_socket.Bind(new IPEndPoint(IPAddress.Parse(address), port));
Receive();
}
public void Client(string address, int port)
{
_socket.Connect(IPAddress.Parse(address), port);
Receive();
}
public void Disconnect()
{
if(_socket.Connected)
_socket.Disconnect(true);
}
public void Send(byte[] data)
{
_socket.BeginSend(data, 0, data.Length, SocketFlags.None, (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndSend(ar);
}, state);
}
public byte[] Receive()
{
_socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
{
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));
}, state);
return state.buffer;
}
}
}