使用一行telnet语句时,C套接字读取输出空字符串

时间:2015-04-06 15:48:27

标签: c sockets telnet

我在使用telnet和echo在一行中通过TCP套接字读取客户端输入时遇到问题。它只适用于我在正常情况下输入消息的情况。 telnet会话:

客户端控制台

devbox cehrig # telnet 127.0.0.1 50231
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Test Message
Connection closed by foreign host.
devbox cehrig # echo "One Liner" | telnet 127.0.0.1 50231
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
Connection closed by foreign host.
devbox cehrig # 

服务器控制台

Mon Apr  6 16:36:41 2015: Accepting connections...
Mon Apr  6 16:36:45 2015: Inbound connection from  127.0.0.1
Client msg: Test Message
Mon Apr  6 16:36:48 2015: Accepting connections...
Mon Apr  6 16:44:06 2015: Inbound connection from  127.0.0.1
Client msg: 
Mon Apr  6 16:44:06 2015: Accepting connections...

"客户信息"尝试使用echo""发送数据时保持空白。 | telnet ....

这是我用来从客户端套接字读取的函数:

void read_socket(int idntef, 
         config_t * cfg)
{
    int n;
    char * _buf = (char *) malloc(512*sizeof(char));
    char * _cor = (char *) malloc(512*sizeof(char));
    char * _out = _cor;

    bzero(_buf, 512);
    bzero(_cor, 512);


    if((n = read(idntef, _buf, 511)) < 0) {
        _print(stderr, "messages.socketreadfail", cfg, 1);
        _exit(0);
    }

    int x = 0;
    while(*_buf != '\n' && x++ <= 512) {
        *_cor++ = *_buf++;
    }

    printf("Client msg: %s\n", _out);
    fflush(stdout);
    shutdown(idntef, 2);
}

sbd对我有什么暗示,这里有什么改进?

1 个答案:

答案 0 :(得分:0)

无法保证数据将在一个块中发送。你需要循环阅读直到&#39; \ n&#39;找到或达到缓冲限制。

类似的东西:

size_t size=0;
do {
    if((n = read(idntef, _buf+size, 512-size)) < 0) {
        _print(stderr, "messages.socketreadfail", cfg, 1);
        _exit(0);
    }
    size += n;
} while(strchr(_buf, '\n') == NULL && size < 512);