为什么我不能收到任何数据?

时间:2019-12-04 15:28:08

标签: c winapi networking serial-port

因此,我计划通过串行端口发送0xff字节,这应该由第二台计算机接收,然后再通过以太网端口发送回数据。但是,一旦发送0xff字节,导致命令行显示“以太网连接超时”,我将不会收到任何数据。我在做什么错了?

#include <stdio.h>
#include <stdlib.h>
#include<windows.h>
#include<winsock2.h>
#include <string.h>
#include <time.h>

#pragma comment(lib,"ws2_32.lib") //Winsock Library
#define BUFLEN 4097 //Max length of buffer
#define PORT 9090 //The port on which to listen for incoming data

int main()
{
    BOOL Status;
    HANDLE ComPort;
    char str[20] = "\\\\.\\COM";
    char input[4] = "";
    printf("Enter COM port: ");
    fgets(input,4,stdin);
    input[strcspn(input, "\n")] = 0;
    strncat(str,input, 5);
    ComPort = CreateFile((const char*)str,                //port name
                      GENERIC_READ | GENERIC_WRITE, //Read/Write
                      0,                            // No Sharing
                      NULL,                         // No Security
                      OPEN_EXISTING,// Open existing port only
                      0,            // Non Overlapped I/O
                      NULL);        // Null for Comm Devices

  if (ComPort == INVALID_HANDLE_VALUE){
      printf("\nError in opening serial port");
      exit(EXIT_FAILURE);}
  else{
      printf("opening serial port successful");
  }
    DCB dcbSerialParams = { 0 }; // Initializing DCB structure
    dcbSerialParams.DCBlength = sizeof(dcbSerialParams);
    Status = GetCommState(ComPort, &dcbSerialParams);

    dcbSerialParams.BaudRate = CBR_115200;  // Setting BaudRate = 115200
    dcbSerialParams.ByteSize = 8;         // Setting ByteSize = 8
    dcbSerialParams.StopBits = ONESTOPBIT;// Setting StopBits = 1
    dcbSerialParams.Parity   = NOPARITY;  // Setting Parity = None

    SetCommState(ComPort, &dcbSerialParams);
    COMMTIMEOUTS timeouts = { 0 };

    timeouts.ReadIntervalTimeout         = MAXWORD; // in milliseconds
    timeouts.ReadTotalTimeoutConstant    = 10000; // in milliseconds
    timeouts.ReadTotalTimeoutMultiplier  = MAXWORD; // in milliseconds
    timeouts.WriteTotalTimeoutConstant   = 0; // in milliseconds
    timeouts.WriteTotalTimeoutMultiplier = 0; // in milliseconds

    char lpBuffer[] = {255};          //0xff byte to send
    DWORD dNoOFBytestoWrite;         // No of bytes to write into the port
    DWORD dNoOfBytesWritten = 0;     // No of bytes written to the port
    dNoOFBytestoWrite = sizeof(lpBuffer);

    SOCKET s;
    struct sockaddr_in server, si_other;
    int slen , recv_len;
    char buf[BUFLEN];
    WSADATA wsa;

    slen = sizeof(si_other) ;

    //Initialise winsock
    if (WSAStartup(MAKEWORD(2,2),&wsa) != 0)
    {
        printf("Failed. Error Code : %d",WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    //Create a socket
    if((s = socket(AF_INET , SOCK_DGRAM , 0 )) == INVALID_SOCKET)
    {
        printf("\nCould not create socket : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }

    //Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( PORT );

    //Bind
    if( bind(s ,(struct sockaddr *)&server , sizeof(server)) == SOCKET_ERROR)
    {
        printf("\nBind failed with error code : %d" , WSAGetLastError());
        exit(EXIT_FAILURE);
    }
    printf("\nBinding successful");
    DWORD timeout = 0.2 * 1000;//0.2 second ethernet timeout
    setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, (const char*)&timeout, sizeof timeout);

    FILE * fPtr;
    char filename[50] = "fpgadat.bin";
    fPtr = fopen((const char*) filename, "wb");//Open file in wb (write) mode.

    // fopen() return NULL if last operation was unsuccessful
    if(fPtr == NULL)
    {
        // File not created hence exit
        printf("Unable to create file.\n");
        exit(EXIT_FAILURE);
    }

    while(1)
    {
        time_t start = time(NULL);
        Status = WriteFile(ComPort,        // Handle to the Serial port
                   lpBuffer,     // Data to be written to the port
                   dNoOFBytestoWrite,  //No of bytes to write
                   &dNoOfBytesWritten, //Bytes written
                   NULL);

    if(Status == 0){
        printf("\nFailed to write to serial port");
        return 0;
    }else{
    printf("\nData successfully written to serial port");
    }
        printf("\nWaiting for data from fpga...");
        fflush(stdout);

        memset(buf,'\0', BUFLEN);//clear the buffer by filling null, it might have previously received data
        //try to receive some data, this is a blocking call
        if ((recv_len = recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen)) == SOCKET_ERROR)
        {
            printf("\nEthernet connection time-out");
            break;

        }

    fwrite(buf , 1 , sizeof(buf) , fPtr );
    printf("%.2f\n", (double)(time(NULL) - start));
    }
    //close file descriptors
    fclose(fPtr);
    CloseHandle(ComPort);
    closesocket(s);
    WSACleanup();

}

0 个答案:

没有答案