服务器端收到UDP错误数据

时间:2017-05-20 09:58:16

标签: java c++ sockets udp

我在Windows上有一个C ++ UDP客户端,在Android上有一个Java UDP服务器。 我想从客户端向服务器发送数据。 当我发送一个简单的" Hello"。

时,我在服务器端获得了错误的值

这是我的代码: 初始化客户端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;
}

发送数据客户端:

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;
}
}

服务器端(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();
        }
    }
}

我没有收到你好'一点都不即使我改变了这个词,我总是收到同样奇怪的结果。 感谢

1 个答案:

答案 0 :(得分:1)

receiveData.length始终为35000,这是数组的大小。

您很可能打算使用实际读取的数据长度,例如

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