我刚刚开始进入C#UDP网络,我想知道我是否可以发送和接收列表。我有来自另一个允许发送字符串的问题的代码,但我想发送一个类型List<KeyValuePair<int, String>>
或SortedDictionary
。这是我发送字符串的代码:
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;
}
此代码适用于“ToString()
”,但从其他计算机查看时,它不会显示列表内容或SortedDictionary
。如果有办法使用UDP数据包发送这些结构,请告诉我。