【发布时间】:2016-05-04 21:27:08
【问题描述】:
我正在寻找有关简单 TCP 服务器功能的一些建议。
第三个if 语句,假设检查token[1] 是文件名还是目录名(工作正常)。我的问题是,打开文件,向客户端显示文件内容,然后关闭文件。我尝试使用文件 I/O 调用,但没有办法做到这一点。非常感谢任何建议。
void processClientRequest(int connSock) {
int received, count = 0;
char *token[] = { (char*)0, (char*)0 };
char path[257], buffer[257];
// read a message from the client
if ((received = read(connSock, path, 256)) < 0) {
perror("receive");
exit(EXIT_FAILURE);
}
path[received] = '\0';
cerr << "received: " << path << endl;
for(char *p = strtok(path, " "); p; p = strtok(NULL, " ")) //sets tokens
token[count++] = p;
if(strcmp(token[0], "GET") != 0) { //if the first "command" was not GET, exit
strcat(buffer, "Must start with GET");
write(connSock, buffer, strlen(buffer));
exit(-1);
}
int rs;
int fd, cnt;
struct stat bufferS;
rs = stat(token[1], &bufferS);
if (S_ISREG(bufferS.st_mode)) { //input was a file
fd = open(token[1], O_WRONLY); //open
cnt = read(fd, buffer, 257); //read
write(connSock, buffer, strlen(buffer));
}
// else, open directory and stuff (code for that has been omitted to save space)
cerr << "done with this client\n";
close(connSock);
}
【问题讨论】:
-
您正在尝试从以只写方式打开的文件描述符进行读取。
标签: c++ linux file-io system-calls tcpserver