我正在编写简单的应用程序,以便通过UDP与arduinos进行动态通信。
我在C#pc app中编写UDP类时遇到了困难。
我没有收到客户回答后结束功能有问题。如果我与正在启用的客户端连接,没有问题,应用程序在收到答案后运行良好且流畅。
STRING_operations str = new STRING_operations();
static int communicationPort = 8888;
string[] arduinoPool = new string[64];
private void populateArduinoPool()
{
for (int i = 0; i < 25; i++)
{
arduinoPool[i] = "192.168.1." + Convert.ToString(170 + i);
}
}
private string mainCommunication(string vIPAdsress, string Message)
{
string answer = string.Empty;
int port = communicationPort;
Console.WriteLine("IP address: " + vIPAdsress);
Console.WriteLine("Message to sent: " + Message);
Byte[] sendBytes = Encoding.ASCII.GetBytes(str.sendString(Message));
Byte[] receiveBytes = null;
var IP = IPAddress.Parse(vIPAdsress);
var udpClient = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
udpClient.ReceiveTimeout = 1000;
udpClient.SendTimeout = 1000;
var sendEndPoint = new IPEndPoint(IP, port);
var receiveEndPoint = new IPEndPoint(IP, port);
var clientReturn = new UdpClient(port);
udpClient.SendTo(sendBytes, sendEndPoint);
Console.WriteLine("Message sent");
try {
receiveBytes = clientReturn.Receive(ref receiveEndPoint);
Console.WriteLine("Message is being receiving");
if (receiveBytes == null || receiveBytes.Length == 0)
{
Console.WriteLine("No answer");
;
}
Console.WriteLine(Encoding.ASCII.GetString(receiveBytes));
answer = str.trimString(Encoding.ASCII.GetString(receiveBytes));
Console.WriteLine("Trimed answer: " + answer);
udpClient.Disconnect(true);
return answer; }
catch (Exception e)
{
Console.WriteLine(e);
return e.ToString();
}
}
public void populateComboBox(ComboBox CB1)
{
Console.WriteLine("Populating arduino pool");
populateArduinoPool();
string message = str.sendString("HELLO");
for (int i = 0; i < 25; i++)
{
Console.WriteLine("Trying to communicate with: " + arduinoPool[i]);
if (mainCommunication(arduinoPool[i], message) == "YO")
{
Console.WriteLine("Established");
CB1.Items.Add(arduinoPool[i]);
}
}
}
public bool checkIfActive(ComboBox CB1)
{
string message = str.sendString("HELLO"); ;
if (mainCommunication(CB1.SelectedText.ToString(), message) == "YO")
return true;
else
return false;
}