I have written this code in C# and have tested this code to ensure it works well. Any other suggestions for this code would be appreciated as I have a number of users who are sending data on this port.
private Socket serverSocket = null;
private List<EndPoint> clientList = new List<EndPoint>();
private byte[] byteData = new byte[1024];
private int port = 1517;
private void button1_Click(object sender, EventArgs e)
{
this.serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
this.serverSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
this.serverSocket.Bind(new IPEndPoint(IPAddress.Any, this.port));
EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
}
private void DoReceiveFrom(IAsyncResult iar)
{
try
{
EndPoint clientEP = new IPEndPoint(IPAddress.Any, 0);
int dataLen = 0;
byte[] data = null;
try
{
dataLen = this.serverSocket.EndReceiveFrom(iar, ref clientEP);
data = new byte[dataLen];
Array.Copy(this.byteData, data, dataLen);
}
catch (Exception e)
{
}
finally
{
EndPoint newClientEP = new IPEndPoint(IPAddress.Any, 0);
this.serverSocket.BeginReceiveFrom(this.byteData, 0, this.byteData.Length, SocketFlags.None, ref newClientEP, DoReceiveFrom, newClientEP);
}
if (!this.clientList.Any(client => client.Equals(clientEP)))
this.clientList.Add(clientEP);
// DataList.Add(Tuple.Create(clientEP, data));
string s = Encoding.ASCII.GetString(data);
}
catch (ObjectDisposedException)
{
}
}
public void Stop()
{
this.serverSocket.Close();
this.serverSocket = null;
this.clientList.Clear();
}