Skip to content

Instantly share code, notes, and snippets.

@djmoth
Created January 19, 2023 11:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save djmoth/0480b5f4abbf05f4639172f1de79c7b3 to your computer and use it in GitHub Desktop.
Save djmoth/0480b5f4abbf05f4639172f1de79c7b3 to your computer and use it in GitHub Desktop.
EndPoint possible cache test
using System.Net;
using System.Net.Sockets;
namespace SocketTest
{
internal class Program
{
static void Main (string[] args)
{
UdpClient receive = new UdpClient (0);
Socket receiveSocket = receive.Client;
EndPoint source = new IPEndPoint (IPAddress.Any, 0);
byte[] buffer = new byte[256];
List<EndPoint> endpoints = new List<EndPoint> ();
new Thread (Send) { IsBackground = true }.Start (receiveSocket.LocalEndPoint);
new Thread (Send) { IsBackground = true }.Start (receiveSocket.LocalEndPoint);
while (true)
{
EndPoint prevSource = source;
receiveSocket.ReceiveFrom (buffer, ref source);
Console.WriteLine ("Received");
bool found = false;
foreach (EndPoint endpoint in endpoints)
{
if (ReferenceEquals (endpoint, source))
{
Console.WriteLine ("Reused EndPoint");
found = true;
break;
}
}
if (!found)
{
Console.WriteLine ("New EndPoint");
endpoints.Add (source);
}
}
}
private static void Send (object endPointAsObj)
{
IPEndPoint endPoint = (IPEndPoint)endPointAsObj;
UdpClient client = new UdpClient ();
client.Connect ("127.0.0.1", endPoint.Port);
byte[] buffer = new byte[256];
for (int i = 0; i < buffer.Length; i++)
buffer[i] = (byte)i;
while (true)
{
client.Send (buffer, buffer.Length);
Console.WriteLine ("Sent");
Thread.Sleep (100);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment