gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 17:17:05 25 4
gpt4 key购买 nike

我在一行中使用 telnet 和 echo 通过 TCP 套接字读取客户端输入时遇到问题。它仅在我在“正常”telnet session 中输入消息时才有效:

客户端控制台

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 ""发送数据时“Client msg”始终为空 |远程登录....

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

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 是否有提示给我,这里需要改进什么?

最佳答案

不保证数据会在一个 block 中发送。您需要循环读取,直到找到“\n”或达到缓冲区限制。

类似于:

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);

关于使用一行 telnet 语句时,C 套接字读取输出空字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29474609/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com