UDP sending and receiving lists

764 views Asked by At

I am just starting to get into C# UDP networking, and I was wondering if I could send and receive lists. I have code from another question which allows for sending strings, but I would like to send a type List<KeyValuePair<int, String>> or a SortedDictionary. This is the code I have for sending strings:

     SortedDictionary<int, String> m_highScorers = new SortedDictionary<int, String>();
     List<KeyValuePair<int, string>> newList = new List<KeyValuePair<int, string>>();

     m_highScorers.Add(1, "Fish");
     m_highScorers.Add(2, "Fish");
     m_highScorers.Add(3, "Koala");
     m_highScorers.Add(4, "Bear");
     m_highScorers.Add(5, "Lion");

     foreach (KeyValuePair<int, string> p in m_highScorers.OrderBy(key => key.Key))
     {
        newList.Add(p);
     }
     byte[] packetData = System.Text.ASCIIEncoding.ASCII.GetBytes(newList.ToString());

     string ServerIP      = "192.168.0.25";
     string IP            = ReturnIPAddress();
     int port             = 80;

     IPEndPoint ep        = new IPEndPoint(IPAddress.Parse(ServerIP), port);

     Socket client        = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
     client.SendTo(packetData, ep);
     Console.Read();
  }

  static string ReturnIPAddress()
  {
     IPHostEntry host;
     string localIP = "?";
     host           = Dns.GetHostEntry(Dns.GetHostName());

     foreach (IPAddress ip in host.AddressList)
     {
        if (ip.AddressFamily.ToString() == "InterNetwork")
        {
           localIP = ip.ToString();               
        }
     }
     return localIP;
  }

This code works fine for the "ToString()" but when looking at it from another computer, it doesn't show the contents of the list or the SortedDictionary. Please let me know if there is a way to send either of these structures using UDP packets.

0

There are 0 answers