Java Server无法通过UDP

时间:2017-04-18 17:19:35

标签: java sockets udp

我有一个C客户端,它使用UDP将数据包发送到我的电脑IP address。以下是用于初始化socket

的函数
void log_init(const char *ipString) {
    log_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    if (log_socket < 0)
        return;

    struct sockaddr_in connect_addr;
    memset(&connect_addr, 0, sizeof(connect_addr));
    connect_addr.sin_family = AF_INET;
    connect_addr.sin_port = 4405;
    inet_aton(ipString, &connect_addr.sin_addr);

    if (connect(log_socket, (struct sockaddr *) &connect_addr, sizeof(connect_addr)) < 0) {
        socketclose(log_socket);
        log_socket = -1;
    }
}

以下是发送代码:

void log_print(const char *str) {
    // socket is always 0 initially as it is in the BSS
    if (log_socket < 0) {
        return;
    }

    int len = strlen(str);
    int ret;
    while (len > 0) {
        int block = len < 1400 ? len : 1400; // take max 1400 bytes per UDP packet
        ret = send(log_socket, str, block, 0);
        if (ret < 0)
            break;

        len -= ret;
        str += ret;
    }
}

Java中,我希望收到这些消息但是它们永远不会到达,它总是停留在receive()上:

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer
{
    public static void main(String[] arguments) throws Exception
    {
        System.out.println("Binding...");
        DatagramSocket serverSocket = new DatagramSocket(4405);
        System.out.println("Binded!");
        byte[] receiveData = new byte[1400];

        while (true)
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            System.out.println("Receiving...");
            serverSocket.receive(receivePacket);
            String sentence = new String(receivePacket.getData());
            System.out.println("Received: " + sentence);
        }
    }
}

有趣的是,与Java服务器在同一台机器上的C服务器工作得很好并且确实收到了消息。 socket初始化和接收函数如下:

int NetInit()
{
    if(sock_id >= 0)
        return sock_id;

#ifdef WIN32
    WSADATA wsaData;

    // Initialize Winsock
    if (WSAStartup(MAKEWORD(2,2), &wsaData) == SOCKET_ERROR)
        return -1;
#endif
    //Get a socket
    if((sock_id = socket(AF_INET, SOCK_DGRAM, IPPROTO_IP)) == -1)
        return -1;

#ifdef WIN32
    u_long mode = 1;
    ioctlsocket(sock_id, FIONBIO, &mode);
#else
    int flags = fcntl(sock_id, F_GETFL, 0);
    fcntl(sock_id, F_SETFL, flags | O_NONBLOCK);
#endif

    return sock_id;
}

int NetRead(void *buffer, unsigned int buf_len)
{
    if(sock_id < 0)
        return sock_id;

    fd_set fdsRead;
    FD_ZERO(&fdsRead);
    FD_SET(sock_id, &fdsRead);

    struct timeval tv;
    tv.tv_sec = 0;
    tv.tv_usec = 10000;

    if(select(sock_id + 1, &fdsRead, NULL, NULL, &tv) != 1) {
        return 0;
    }

    int len = sizeof(servaddr);

    return recvfrom(sock_id,buffer, buf_len, 0,(struct sockaddr *)&servaddr, &len);
}

如何接收与Java一起使用的消息?

0 个答案:

没有答案