0

UDP サーバーとしてハードウェア ARM コントロールがあり、C# で記述された以下のコードを介して通信しています。PC は UDP クライアントです。サーバーは単にデータをエコーし​​ます。

これは問題なく正常に動作し、安定しています。

using System.Net.Sockets;
using System.Net;
using System.Text;
using System;

namespace UDPSocket
{
    class UDPSender
    {
        static void Main(string[] args)
        {
            UInt32 i=0;
            Int32 PORT = 45555;
            for (; i < 15; )
            {
                Console.WriteLine(i++);
                Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Dgram,
                    ProtocolType.Udp);

                IPAddress broadcast = IPAddress.Parse("192.168.0.10");

                byte[] sendbuf = Encoding.ASCII.GetBytes("Shriganesh Damle, Infineon Techonologies India Pvt Ltd, Bangalore");
                IPEndPoint ep = new IPEndPoint(broadcast, PORT);

                //Creates a UdpClient for reading incoming data.
                UdpClient receivingUdpClient = new UdpClient(PORT);

                s.SendTo(sendbuf, ep);

                Console.WriteLine("Message sent to the broadcast address");

                //Creates an IPEndPoint to record the IP Address and port number of the sender.  
                // The IPEndPoint will allow you to read datagrams sent from any source.
                IPEndPoint RemoteIpEndPoint = new IPEndPoint(IPAddress.Any, 0);

                // Blocks until a message returns on this socket from a remote host.
                Byte[] receiveBytes = receivingUdpClient.Receive(ref RemoteIpEndPoint);

                string returnData = Encoding.ASCII.GetString(receiveBytes);

                Console.WriteLine("This is the message you received " +
                                            returnData.ToString());
                Console.WriteLine("This message was sent from " +
                                            RemoteIpEndPoint.Address.ToString() +
                                            " on their port number " +
                                            RemoteIpEndPoint.Port.ToString());
                //Console.Read();
                receivingUdpClient.Close();
            }
            Console.Read();
        }
    }
}

ここで、Win32 C アプリケーションで同じ PC コードが必要です。以下のコードを試しました。

/*
    Simple udp client    
*/
#include<stdio.h>
#include<winsock2.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library

#define SERVER "192.168.0.10"  //ip address of udp server
#define BUFLEN 512  //Max length of buffer
#define PORT 45555   //The port on which to listen for incoming data

int main(void)
{
    struct sockaddr_in si_other;
    int s, slen=sizeof(si_other);
    char buf[BUFLEN];
    char message[BUFLEN];
    WSADATA wsa;

    //Initialise winsock
    printf("\nInitialising Winsock...");
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("Initialised.\n");

    //create socket
    if ( (s=socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR)
    {
        printf("socket() failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    //setup address structure
    memset((char *) &si_other, 0, sizeof(si_other));
    si_other.sin_family = AF_INET;
    si_other.sin_port = htons(PORT);
    si_other.sin_addr.S_un.S_addr = inet_addr(SERVER);

    //start communication
    while(1)
    {
        printf("Enter message : ");
        gets(message);

        //send the message
        if (sendto(s, message, strlen(message) , 0 , (struct sockaddr *) &si_other, slen) == SOCKET_ERROR)
        {
            printf("sendto() failed with error code : %d" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }

        //receive a reply and print it
        //clear the buffer by filling null, it might have previously received data
        memset(buf,'\0', BUFLEN);
        //try to receive some data, this is a blocking call
        if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == SOCKET_ERROR)
        {
            printf("recvfrom() failed with error code : %d" , WSAGetLastError());
            exit(EXIT_FAILURE);
        }

        puts(buf);
    }

    closesocket(s);
    WSACleanup();

    return 0;
}

このコードは UDP サーバーに送信でき、エコー バックします。しかし、recvfrom 呼び出しは無限の時間までデータを待機します。recvfrom が呼び出しをブロックしています。正しい IP アドレスと PORT を指定しています。それでも、Win32 アプリでサーバーからデータを受信できません。手伝ってくれますか?

4

1 に答える 1

1

ソケットでデータを受信したい場合は、それを 1 つ以上のローカル アドレスとローカル ポートにバインドする必要があります。あなたの C# バージョンnew UdpClient(PORT)は (引数に注意してPORTください) 経由でこれを実現しますが、あなたの C バージョンはこれに匹敵することは何もしません。

ソケットを作成したら、

sockaddr_in localAddr;

localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(PORT);
localAddr.sin_addr.S_un.S_addr = INADDR_ANY;

bind(s, &localAddr, sizeof(sockaddr_in));

0成功を示すために返されることを確認します。

または、サーバーの応答を受信するための 2 つ目のソケットを作成した場合、C バージョンは C# バージョンと同等になります。C (より正確には Winsock2) でそれを行う必要はないと思いますが、送信と受信の両方に同じソケットを使用するには、 to ではなく特定のローカル アドレスにバインドする必要がある可能性がありますINADDR_ANY

于 2015-03-27T15:01:29.617 に答える