gpt4 book ai didi

c - tcp 服务器阻塞读取 C

转载 作者:可可西里 更新时间:2023-11-01 02:45:09 24 4
gpt4 key购买 nike

我想实现一个带有阻塞读取的简单 TCP 服务器,它接收从客户端发送的消息,一个字符一个字符地接收消息,直到一个分隔符。一旦收到一条消息,它必须等到下一条消息出现。这是我的伪代码:

// Messages sent from the client
char *message1 = "mssg1\n"
char *message2 = "mssg2\n"

// On server side
char buffer;
char completeMessage[5]

while(1){

while(buffer != '\n'){
recv(sock, &buffer, 1, 0); // 1 is the read size

if(buffer != '\n') {
printf("buffer: %c\n", buffer);
completeMessage[n] = buffer;
count ++;
}
else{
printf("Complete message: %s\n", completeMessage);
count = 0;
}
}
}

结果如下:

buffer: m
buffer: s
buffer: s
buffer: g
buffer: 1
Complete message: mssg1
buffer:
buffer:
buffer:
buffer:
buffer:
buffer:
// Error due to buffer overflow

我不知道为什么 recv 不是等待下一个消息字符(阻塞读取),而是继续读取空格。我的问题如下:

  • recv 真的是套接字阻塞读函数吗?
  • 代码中是否有错误或缺失?
  • 还有其他实现此建议的建议吗?

最佳答案

Is recv really a socket blocking read function?

是的,除非您将句柄设为非阻塞。

Is there something wrong or missing in the code?,

  • 您没有检查 recv 返回的内容。 0表示EOF,-1表示错误。

  • 您不检查缓冲区有多满,因此有缓冲区溢出的风险。

  • 您没有按照 printf %s 的要求使用 NUL 终止 completeMessage 中的字符串。

Any other suggestions for implementing this?

你不应该一次读一个字符!


#define BUFFER_SIZE (64*1024)

char* extract_string(const char* start, const char* end) {
size_t len = end - start;
char* dst = malloc(len+1);
if (dst == NULL)
return NULL;

memcpy(dst, src, len);
dst[len] = '\0';
return dst;
}

{
char buf_start[BUFFER_SIZE];
char* buf_end = buf_start + BUFFER_SIZE;
char* window_start = buf_start;
char* window_end = buf_start;
while (1) {
if (window_end == buf_end) { // No more space.
fprintf(stderr, "Overly large message");
return 0;
}

ssize_t rv = recv(sock, window_end, buf_end-window_end, 0);
if (rv == -1) { // Error.
perror("recv");
return 0;
}

if (rv == 0) { // EOF.
return 1;
}

while (rv--) {
if (*(window_end++) == '\n') {
char* msg = extract_string(window_start, window_end-1); // Excl LF.
if (msg == NULL) {
fprintf(stderr, "Out of memory");
return 0;
}

// Do something with msg
printf("Complete message: %s\n", msg);
free(msg);

window_start = window_end;
}
}

memmove(buf_start, window_start, window_end-window_start);
window_end -= (window_start - buf_start);
window_start = buf_start;
}
}

关于c - tcp 服务器阻塞读取 C,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43923475/

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