我无法在用 C++ 编写的服务器和用 C# 编写的客户端之间建立 UDP 连接

I am unable to establish UDP Connection between Server written in C++ and Client written in C#

在 C++ 和 C# 应用程序之间使用 UDP 发送和接收数据
这是我的两个应用程序,一个用 c++ 编写的服务器和一个用 c# 编写的客户端。当我编译和 运行 这两个应用程序时,我没有收到任何数据。

服务器控制台应用程序 (C++)

 #include "iostream"
 #include "winsock2.h"

 using namespace std ;

void main()

{
WSADATA wsaData;
SOCKET SendSocket;
sockaddr_in RecvAddr;
int Port = 27250;   //port number

char SendBuf[32]="From port 27250";

int BufLen = 32;

char* IP_ADDRESS_S="127.0.0.1";    //IP Address


WSAStartup(MAKEWORD(2,2), &wsaData);


SendSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);

RecvAddr.sin_family = AF_INET;

RecvAddr.sin_port = htons(Port);

RecvAddr.sin_addr.s_addr = inet_addr(IP_ADDRESS_S);

cout<<"Sending a datagram to the receiver...";

sendto(SendSocket, SendBuf, BufLen, 0, (SOCKADDR *) &RecvAddr, 
sizeof(RecvAddr));

cout<<"Finished sending. Closing socket.";

closesocket(SendSocket);

cout<<"Exiting.";

WSACleanup();


}

客户端控制台应用程序 (C#)

使用 UdpClient class

用 C# 编写的 udp client/receiver
   using System;
   using System.Net;
   using System.Net.Sockets;
   using System.Text;
 namespace UDPServer {

 class Program {

  static void Main(string[] args {

  RecData(27250); }       //Port number

  static void RecData(int Port) {

  UdpClient client = null;

  try {
   client = new UdpClient(Port);
     }

  catch (Exception ex)
     {

   Console.WriteLine(ex.Message);
    }
    // IPAddress addr=IPAddress.Parse("127.0.0.1");
   IPEndPoint RemoteServer = new IPEndPoint(IPAddress.Any, 0); //IP address

   for (; ; )

   {

   try {

  byte[] RecPacket = client.Receive(ref RemoteServer);

  Console.WriteLine("Connected to the client {0}, {1}", RemoteServer, 
   Encoding.ASCII.GetString(RecPacket));

   }
  catch (Exception ex)

   {
 Console.WriteLine(ex.Message);

  }}

  }}

  }
      *** 

Finally got solution


我的客户端应用程序代码中存在一些错误。所以这是解决方案。

        static void Main(string[] args)
       {
        Console.WriteLine("App Started...");
        ReceiveData();
        //Console.ReadKey();
       }
     static IPAddress addr = IPAddress.Parse("127.0.0.1");
     static IPEndPoint ep = new IPEndPoint(addr, 0);
     static UdpClient udpClient = new UdpClient(28280);
     static byte[] receiveBytes = new byte[32];
     static string returnData = "";


    static void ReceiveData()
    {
        while (true)
        {

            receiveBytes = udpClient.Receive(ref ep);
            returnData = Encoding.ASCII.GetString(receiveBytes);
            Console.WriteLine("Data receiving..."+returnData);   
        }
    }
}