简体   繁体   中英

UDP wrong data received server side

I got a C++ UDP client on Windows and a Java UDP Server on Android. I would like to send data from client to the server. I got wrong values on server side when I send a simple "Hello".

Here is my code : Init client C++

int Socket::createUDPSocket(char *ip) {
int i_result = WSAStartup(MAKEWORD(2, 2), &mWSAData);

mSocket = socket(AF_INET, SOCK_DGRAM, 0);
if (mSocket == SOCKET_ERROR || mSocket == INVALID_SOCKET) {
    WSACleanup();
    return i_result;
}

RtlZeroMemory(&mUdpConf, sizeof(mUdpConf));
mUdpConf.sin_family = AF_INET;
mUdpConf.sin_addr.s_addr = inet_addr(ip);
mUdpConf.sin_port = htons(DEFALT_UDP_PORT);

i_result = connect(mSocket, (struct sockaddr *) &mUdpConf, sizeof(mUdpConf));
if (i_result == SOCKET_ERROR) {
    closesocket(mSocket);
    mSocket = INVALID_SOCKET;
    return i_result;
}

return i_result;
}

Send data client side :

void Socket::sendUdpData(char *data, int size) {
int result = sendto(mSocket, data, size, 0, (struct sockaddr *) &mUdpConf, sizeof(mUdpConf));
if (result == SOCKET_ERROR) {
    closesocket(mSocket);
    WSACleanup();
    return;
}
}

Server Side (Java) :

private class ServerUDPThread implements Runnable {
    @Override
    public void run() {
        DatagramSocket serverSocket;
        try {
            serverSocket = new DatagramSocket(null);
            serverSocket.setReuseAddress(true);
            serverSocket.setReceiveBufferSize(35000);
            serverSocket.bind(new InetSocketAddress(5010));
            byte[] receiveData = new byte[35000];
            while (!Thread.currentThread().isInterrupted()) {
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                if (receiveData.length > 0) {
                    System.out.println("Size UDP packet received = " + receivePacket.getLength());
                    getBufferSocketUDP(receiveData.length, receiveData);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I don't receive 'Hello' at all. I always receive same weird result even if I change the word.. Thanks

receiveData.length is always 35000 which is the size of the array.

Most likely you intended to use the length of data actually read which eg

serverSocket.receive(receivePacket);
if (receivePacket.getLength() > 0) {
    System.out.println("Size UDP packet received = " + receivePacket.getLength());
    getBufferSocketUDP(receivePacket.getLength(), receiveData);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM