我正在尝试使用线程在Linux中实现客户端服务器聊天,但是会遇到奇怪的行为。 我正在尝试从客户端获取消息到缓冲区,然后将消息发送给他,但我只收到消息,消息不会发送回客户端。可能是什么原因 ?? 代码说明: 我正在为服务器打开一个FIFO,以便其他客户端可以使用特殊消息连接到它。为此,我创建了一个只执行此任务的线程。 客户端连接后,我正在与客户端通过2个FIFO进行通信: 一个用于传入消息,一个用于传出消息。 现在我尝试做的是从已连接到服务器的客户端获取消息,然后使用两个线程将其发送回给他,每个线程用于写入或读取目的,但我只能成功从客户端获取消息,但客户无法取回它。 可能是什么问题? 非常感谢你提前!
来源附件。
#include <unistd.h>
#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <pthread.h>
#define MAX_MESSAGE_LENGHT 10240
void server_signal_handler();
void *server_fifo_read_thread(int id);
void *server_fifo_write_thread(int id);
void *server_main_fifo_connection();
char mess_buffer[1000];
int main() {
char server_fifo_path[] = "/tmp/server-fifo";
int server_fifo = mkfifo(server_fifo_path, 0666);
if (server_fifo < 0) {
printf("Error creating server fifo\n");
return -1;
}
server_fifo = open(server_fifo_path, O_RDONLY);
if (server_fifo < 0) {
printf("Error opening file");
return -1;
}
pthread_t server_main_fifo_thread;
pthread_create(&server_main_fifo_thread, NULL, server_main_fifo_connection, (int*)server_fifo);
pthread_join(server_main_fifo_thread, NULL);
}
void *server_main_fifo_connection(int server_fifo){
while (1){
char buffer[MAX_MESSAGE_LENGHT];
while (read(server_fifo, buffer, MAX_MESSAGE_LENGHT) == 0); // Wait for client initial message
int message_length = *((int*)buffer);
int client_id = *( (int*)(buffer + sizeof(int)) );
char* client_name = (char*)malloc(sizeof(char) * (message_length + 1));
memcpy(client_name, buffer + 2*sizeof(int), message_length);
client_name[message_length+1] = '\0';
pthread_t write_thread;
pthread_create(&write_thread, NULL, server_fifo_write_thread, (int*)client_id);
}
}
void *server_fifo_write_thread(int id){
int write_fifo;
char fifo_write_path[20];
sprintf(fifo_write_path, "/tmp/fifo-%d-in", id);
write_fifo = open(fifo_write_path, O_WRONLY);
if (write_fifo < 0){
printf("Error opening write FIFO");
return;
}
pthread_t read_thread;
pthread_create(&read_thread, NULL, server_fifo_read_thread, (int*)id);
write(write_fifo, "/ack", 5);
while(1){
write(write_fifo, mess_buffer, strlen(mess_buffer));
}
}
void *server_fifo_read_thread(int id){
int read_fifo;
char fifo_read_path[20];
sprintf(fifo_read_path, "/tmp/fifo-%d-out", id);
read_fifo = open(fifo_read_path, O_RDONLY);
if (read_fifo < 0){
printf("Error opening read FIFO");
return;
}
while(1){
while (read(read_fifo, mess_buffer, strlen(mess_buffer)) == 0);
}
}