如何检查数据是否到达TCP套接字?

时间:2014-01-24 16:22:51

标签: c sockets tcp ip port

SOCKET sock;
SOCKET fd;
uint8* pChunkData;
uint16 chunkLen;
uint16 port = 52428;


void CreateSocket() {
    struct sockaddr_in server, client;  // creating a socket address structure: structure contains ip address and port number
    WORD wVersionRequested;
    WSADATA wsaData;
    int len;
    int iResult;

    u_long iMode = 0;
    int sockoptval = 1;

    printf("Initializing Winsock\n");

    wVersionRequested = MAKEWORD (1, 1);
    iResult =  WSAStartup (wVersionRequested, &wsaData);      
    if (iResult != NO_ERROR)
    printf("Error at WSAStartup()\n"); 

    // create socket
    sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    if (sock < 0) {
        printf("Could not Create Socket\n");
        //return 0;
    }

    printf("Socket Created\n");

    setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char *)&sockoptval, 1);

    iResult = ioctlsocket(sock, FIONBIO, &iMode);
    if (iResult != NO_ERROR)
    printf("ioctlsocket failed with error: %ld\n", iResult);

    // create socket address of the server
    memset( &server, 0, sizeof(server));

    // IPv4 - connection
    server.sin_family = AF_INET;
    // accept connections from any ip adress
    server.sin_addr.s_addr = htonl(INADDR_ANY);
    // set port
    server.sin_port = htons(52428);

    //Binding between the socket and ip address
    if(bind (sock, (struct sockaddr *)&server, sizeof(server)) < 0) {
        printf("Bind failed with error code: %d", WSAGetLastError());
    }


    //Listen to incoming connections
    if(listen(sock, 3) == -1) {
        printf("Listen failed with error code: %d", WSAGetLastError());
    }

    printf("Server has been successfully set up - Waiting for incoming connections");

    for(;;) {
        len = sizeof(client);
        fd = accept(sock, (struct sockaddr*) &client, &len);

        if (fd < 0){
        printf("Accept failed");
        //closesocket(sock);
        }
        //echo(fd);

        printf("\n Process incoming connection from (%s , %d)", inet_ntoa(client.sin_addr),ntohs(client.sin_port));
    }
}

void main() {
    HANDLE h1,h2,h3;
    int bytes_recieved;

    double Task2ms_Raster, Task10ms_Raster, Task100ms_Raster ;

    pChunkData = &recv_data;
    chunkLen = sizeof(pChunkData);

    CreateSocket();

    while(1) {
        bytes_recieved = recv(fd, recv_data, 100 , 0 );
        recv_data[bytes_recieved] = '\0';
    }                         
    XcpIp_RxCallback (chunkLen, *pChunkData, port);
}

以上是服务器端程序,它接受来自主服务器的连接。我想打电话 每当我在套接字XcpIp_RxCallback (chunkLen, *pChunkData, port);上收到数据时,fd API。谁能告诉我怎么做?

2 个答案:

答案 0 :(得分:1)

关闭'while(1){.. recv()..}循环。

答案 1 :(得分:1)

您的代码没有意义。

你的CreateSocket()方法循环永远接受连接并忽略它们,所以在main()中从socket读取它之后的代码是无法访问的。

您应该为每个为该会话执行I / O的已接受套接字生成一个线程。

如果在任何系统调用中出现错误,只打印一个字符串,甚至没有实际错误,然后继续进行,就好像没有发生错误一样,这是不够的缓解。

此代码中没有必要将侦听套接字设置为非阻塞模型