我对此任务感到困惑。我需要实现一个C ++程序,该程序在循环中侦听端口以接收来自客户端的TCP请求。对于每个接受的传入请求,它会派一个孩子来读取和处理该请求。父进程继续以无限循环的方式侦听并接受传入的TCP请求。
程序接受2个命令行参数:
要监听的端口号,目录的路径名,该目录用作所有请求的文件或目录的根。您能帮我吗?
/*
* TCPClient.cxx
*
* TCP client
*
* sends message to TCP server
* waits for message received from server
*
* command line arguments:
* argv[1] FQDN of server
* argv[2] port number to send to
* argv[3] request to send
*
*/
#include <sys/socket.h>
#include <netdb.h>
#include <unistd.h>
#include <cstdlib>
#include <cstring>
#include <cstdio>
#include <iostream>
using namespace std;
int main(int argc, char *argv[]) {
if (argc != 4) {
cerr << "USAGE: TCPClient server_name port request\n";
exit(EXIT_FAILURE);
}
// lookup FQDN
struct addrinfo *res, hints;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
int error = getaddrinfo(argv[1], argv[2], &hints, &res);
if (error) {
cerr << argv[1] << ": " << gai_strerror(error) << endl;
exit(EXIT_FAILURE);
}
char buffer[1024];
int sent, received;
// Create the TCP socket
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock < 0) {
perror("Failed to create socket");
exit(EXIT_FAILURE);
}
// connect to server
if (connect(sock, res->ai_addr, res->ai_addrlen) < 0) {
perror("connect");
exit(EXIT_FAILURE);
}
// Send the message string to the server
sent = write(sock, argv[3], strlen(argv[3])+1);
if (sent < 0) {
perror("write");
exit(EXIT_FAILURE);
}
// Receive the message back from the server
do {
received = read(sock, buffer, sizeof(buffer));
if (received < 0) {
perror("read");
exit(EXIT_FAILURE);
}
cout.write(buffer, received);
} while (received > 0);
cout << endl;
close(sock);
}
[创建套接字时,我看不到您打电话给bind(),listen()
以等待客户端连接,请给我更多信息。