在C ++和C#应用程序之间使用UDP发送和接收数据
这是我的两个应用程序,一个用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#编写的udp客户端/接收器
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);
}}
}}
}
答案 0 :(得分:0)
***
终于得到了解决方案
我的客户端应用代码存在一些错误。所以这是解决方案。 的
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);
}
}
}