matlab与c之间的tcp连接

时间:2015-02-22 09:40:07

标签: c matlab tcp

1. 摘要:
我在C中编写了一个代码,将键盘上按下的单个字符传输到matlab,matlab将接收它并打印出来。但问题是matlab没有立即响应,例如当我在终端中按“a”时,matlab应立即响应,但这不会发生。 matlab需要一段时间(可能是~10到15秒),并将当时按下的所有字符作为一个块接收并打印出来,

2.例如:< / strong>
如果我在终端(C部分)输入字母:ab和c,matlab应该打印:

label =

label =

B'/ P>

label =

C

但matlab打印以下内容:

label =

ABC

3.Implementation   

C代码:

int main(int argc, char *argv[])
{
     int listenfd = 0, connfd = 0 , n = 0 ;
    struct sockaddr_in serv_addr;   

    listenfd = socket(AF_INET, SOCK_STREAM, 0);
    serv_addr.sin_family = AF_INET;
    serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
    serv_addr.sin_port = htons(5000);
    bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr));

    listen(listenfd, 1);
            connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);        
static struct termios oldt, newt;

    /*tcgetattr gets the parameters of the current terminal
    STDIN_FILENO will tell tcgetattr that it should write the settings
    of stdin to oldt*/
    tcgetattr( STDIN_FILENO, &oldt);
    /*now the settings will be copied*/
    newt = oldt;

    /*ICANON normally takes care that one line at a time will be processed
    that means it will return if it sees a "\n" or an EOF or an EOL*/
    newt.c_lflag &= ~(ICANON);          

    /*Those new settings will be set to STDIN
    TCSANOW tells tcsetattr to change attributes immediately. */
    tcsetattr( STDIN_FILENO, TCSANOW, &newt);

    /*This is your part:
    I choose 'e' to end input. Notice that EOF is also turned off
    in the non-canonical mode*/
    char character_old = getchar();

    while((character_old != '.'))
    {   


    char character_new = getchar();



    if ( ( write(connfd, &character_new, sizeof(char))) < 0)
    {
        printf("\n ERROR IN WRITE \n") ;
    }
    character_old = character_new ;
    printf("character \n : %c\n",character_old);
    }   
    tcsetattr( STDIN_FILENO, TCSANOW, &oldt);
close(connfd);
    return 0;
}

Matlab代码:

function [l label]  = test()
l = tcpip('127.0.0.1' , 5000) ;
l.BytesAvailableFcnMode = 'byte' ;
l.BytesAvailableFcnCount =1;
fopen(l);
x = 1 ; 
while (x==1)
        label = fscanf(l , '%c');
        label 
    end
end

0 个答案:

没有答案