2010-02-09 154 views
-1

我寫在C計劃,我想知道我怎麼可以聽COM端口 並從中 讀取數據,請幫我 感謝聽COM端口

+4

使用COM端口是操作系統特定的,因此您需要告訴我們您希望使用哪種操作系統。 – 2010-02-09 06:45:27

+2

操作系統特定*和*特定環境。只是標準的C庫?任何框架? – 2010-02-09 06:47:43

+0

您在評論中指出您正在爲嵌入式系統開發,但未提及您將使用的操作系統。 Linux呢?視窗? BSD?也許還有別的東西? – 2010-02-09 07:35:18

回答

1

我不知道你是什麼樣的尋找,但是這可能是一些幫助,它在Unix上:

#include <stdio.h> 
#include <sys/types.h> 
#include <sys/socket.h> 
#include <netinet/in.h> 
#include <bstring.h>   /* bzero(), bcopy() */ 
#include <unistd.h>   /* read(), write(), close() */ 
#include <errno.h> 
#include <sys/signal.h> 

int obtain_socket(int port); 
void show_message(int sd); 
void close_down(int sigtype); 


#define PORT 2001   /* default port for server */ 
#define SIZE 512   /* max length of character string */ 

int ssockfd;  /* socket for PORT; global for close_down() */ 

int main() 
{ 
    int sd, client_len; 
    struct sockaddr_in client; 

    signal(SIGINT, close_down); /* use close_down() to terminate */ 

    printf("Listen starting on port %d\n", PORT); 
    ssockfd = obtain_socket(PORT); 
    while(1) { 
    client_len = sizeof(client); 
    if ((sd = accept(ssockfd, (struct sockaddr *) &client, 
         &client_len)) < 0) { 
     perror("accept connection failure"); 
     exit(4); 
    } 
    show_message(sd); 
    close(sd); 
    } 
    return 0; 
} 


int obtain_socket(int port) 
/* Perform the first four steps of creating a server: 
    create a socket, initialise the address data structure, 
    bind the address to the socket, and wait for connections. 
*/ 
{ 
    int sockfd; 
    struct sockaddr_in serv_addr; 

    /* open a TCP socket */ 
    if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { 
    perror("could not create a socket"); 
    exit(1); 
    } 

    /* initialise socket address */ 
    bzero((char *)&serv_addr, sizeof(serv_addr)); 
    serv_addr.sin_family = AF_INET; 
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY); 
    serv_addr.sin_port = htons(port); 

    /* bind socket to address */ 
    if (bind(sockfd, (struct sockaddr *)&serv_addr, sizeof(serv_addr)) < 0) { 
    perror("could not bind socket to address"); 
    exit(2); 
    } 

    /* set socket to listen for incoming connections */ 
    /* allow a queue of 5 */ 
    if (listen(sockfd, 5) == -1) { 
    perror("listen error"); 
    exit(3); 
    } 
    return sockfd; 
} 


void show_message(int sd) 
/* Print the incoming text to stdout */ 
{ 
    char buf[SIZE]; 
    int no; 

    while ((no = read(sd, buf, SIZE)) > 0) 
    write(1, buf, no); /* write to stdout */ 
} 


void close_down(int sigtype) 
/* Close socket connection to PORT when ctrl-C is typed */ 
{ 
    close(ssockfd); 
    printf("Listen terminated\n"); 
    exit(0); 
} 
+0

嗨,我想在一個嵌入式系統上運行這個程序 – Mehdi 2010-02-09 07:29:47

+0

你使用什麼編譯器爲系統?在所有情況下,只要嘗試編譯這個程序,看看你得到了什麼。 – Vivek 2010-02-09 07:40:13

+0

謝謝Vivek。我在Linux上編譯了以下內容:將更改爲。添加「包括」。 – 2018-02-26 21:30:21