UDP通信的一些笔记

在本例中,采用Java进行发送,采用C++编写接收端的程序(从MSDN中撷取而来,可以说得上是经得住考验的)。

下面部分是C++写的一个UDP的接收方

#pragma comment(lib, "Ws2_32.lib")
/// 这个很重要
// Link with ws2_32.lib

#include 
#include 
#include 

int main(void)
{
    //// 下面是MSDN上面的例程,比较标准了
    int iResult = 0;

    WSADATA wsaData;

    //-----------------------------------------------
    // Initialize Winsock
    iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
    if (iResult != NO_ERROR) {
        printf("WSAStartup failed with error %d\n", iResult);
        return 1;
    }
    //-----------------------------------------------
    // Create a receiver socket to receive datagrams
    SOCKET RecvSocket;
    RecvSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (RecvSocket == INVALID_SOCKET) {
        wprintf(L"socket failed with error %d\n", WSAGetLastError());
        return 1;
    }
    //-----------------------------------------------
    // Bind the socket to any address and the specified port.
    //// 输入发送源的信息,包括IP地址和发送的端口:数据是从这个端口和这个IP过来的

    sockaddr_in RecvAddr;

    unsigned short Port = 6524;
    RecvAddr.sin_family = AF_INET;
    RecvAddr.sin_port = htons(Port);
    //RecvAddr.sin_addr.s_addr = htonl(INADDR_ANY);
    RecvAddr.sin_addr.s_addr = inet_addr("127.0.0.1");

    iResult = bind(RecvSocket, (SOCKADDR *) & RecvAddr, sizeof (RecvAddr));
    if (iResult != 0) {
        wprintf(L"bind failed with error %d\n", WSAGetLastError());
        return 1;
    }
    //-----------------------------------------------
    // Call the recvfrom function to receive datagrams
    // on the bound socket.
    sockaddr_in SenderAddr;
    int SenderAddrSize = sizeof (SenderAddr);

    char RecvBuf[1024];
    int BufLen = 1024;

    wprintf(L"Receiving datagrams...\n");
    while (true)
    {
        memset(RecvBuf, 0, 1024);
        iResult = recvfrom(RecvSocket,
            RecvBuf, BufLen, 0, (SOCKADDR *) & SenderAddr, &SenderAddrSize);
        if (iResult == SOCKET_ERROR) {
            wprintf(L"recvfrom failed with error %d\n", WSAGetLastError());
        }
        else
        {
            printf(RecvBuf);
            printf("\n");
        }
    }

    //-----------------------------------------------
    // Close the socket when finished receiving datagrams
    wprintf(L"Finished receiving. Closing socket.\n");
    iResult = closesocket(RecvSocket);
    if (iResult == SOCKET_ERROR) {
        wprintf(L"closesocket failed with error %d\n", WSAGetLastError());
        return 1;
    }

    //-----------------------------------------------
    // Clean up and exit.
    wprintf(L"Exiting.\n");
    WSACleanup();
    return 0;
}

下面部分是JAVA写的UDP发送方:可以看到,在JAVA的发送放程序中,并不涉及到bind操作。因为其是通过创建一个datagramSocket,然后将目的地址和目的端口放到了DatagramPacket中。

package com;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.UnknownHostException;

public class UDPServ {
    private DatagramSocket dgs = null;
    public UDPServ()
    {
        try {
            dgs = new DatagramSocket();
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("creating new serversocket failure" + e.toString());
        }
    }

    public void send(String addr, int port, String content) 
    {
        byte[] buf = content.getBytes();
        InetAddress dstAddr = null;
        try {
            dstAddr = InetAddress.getByName(addr);
        } catch (UnknownHostException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        try {
            DatagramPacket dPacket = new DatagramPacket(buf, buf.length, dstAddr, port);
            if (null != dgs) 
            {
                dgs.send(dPacket);
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }       
    }

    public static void main(String args[])
    {
        int n = 0;
        UDPServ udpServ = new UDPServ();
        while (n < 8) 
        {
            n = n + 1;
            udpServ.send("127.0.0.1", 6524, "content to send" + Integer.toString(n));
            System.out.println("send" + "content to send" + Integer.toString(n) + "to " + "127.0.0.1:" + Integer.toString(6524));
        }
    }
}

你可能感兴趣的:(工作上的学习)