如何接收和发送数据从服务器到客户端循环
问题描述:
如何保持连接从连接的客户端侦听?在下面的代码中,线程接收数据并回复客户端并断开连接。我想把接收和发送的过程放在循环中。我怎样才能做到这一点 ?如何接收和发送数据从服务器到客户端循环
void *thread_handle_connection(void *arg) {
char buffer[MAX_MSG_SIZE]; // Receive buffer
int bytes_read;
do {
// If there aren't any connections, sleep and recheck every second
while(!num_connections && !term_requested) {
sleep(1);
}
// Lock out connections queue and grab the first one
pthread_mutex_lock(&queue_mutex);
int connectionfd = remove_connection_from_queue();
pthread_mutex_unlock(&queue_mutex);
if(-1 == connectionfd) {
continue;
}
// pthread_barrier_wait(&barrier); // Barrier for threads - for testing only
// Read up to 1024 bytes from the client
bytes_read = recv(connectionfd, buffer, MAX_MSG_SIZE - 1, 0);
// If the data was read successfully
if(bytes_read > 0) {
// Add a terminating NULL character and print the message received
buffer[bytes_read] = '\0';
// Calculate response
int multiplicand = atoi(buffer);
char *response;
asprintf(&response, "%d", multiplicand * MULTIPLIER);
// Echo the data back to the client; exit loop if we're unable to send
if(-1 == send(connectionfd, response, strlen(response), 0)) {
warn("Unable to send data to client");
break;
}
free(response);
}
// Close connection
close(connectionfd);
} while(bytes_read > 0 && !term_requested);
return NULL;
}
答
首先,recv
功能并不能保证你看的已经被写入发送者的一切。您可能会收到部分数据(例如,发件人可能会发送10KByte,但第一次读取时接收人可能会收到1.5K)。
其次,send
函数不能保证它发送你要求的所有东西。如果不是所有东西都已发送,您需要发送其余的答案。
第三,TCP是面向流的。这意味着你需要将一条消息与另一条消息分开。对于基于文本的协议,通常使用“新行”来达到此目的。
放在一起。如果你想申请永久连接,你需要:
- 定义请求和响应分离
- 保持读取缓冲
- 读取所有数据到缓冲区,并扫描它要求分离器与反应分离器
- 发送响应
如果你想在网络编程中取得成功,你可能想了解一些关于非阻塞操作和轮询/选择功能的知识。
你到底在问什么? – zmbq
那么在实际的循环中包装接收代码将是一个好的开始。然后只需在该循环中读写,直到出现错误或连接关闭。 –