我正在编写客户端-服务器应用程序。到目前为止一切正常,客户端发送了一个请求,服务器接收到它,解析它。但是现在我想发回一个答案,所以我复制了这两个函数,我把 write() 从客户端放到服务器,把 read() 从服务器放到客户端。
当我现在运行程序时,一切都阻塞了,服务器等待,客户端也在等待。当我 ctrl+c 客户端时,服务器解除阻塞并解析正确的请求并等待另一个请求。请问有什么问题吗?
来自客户端的部分代码:
params.port = atoi(params.pvalue.c_str());
hostent *host;
sockaddr_in socketHelper;
int clientSocket;
char buf[BUFFER_LEN];
int size;
string data;
string recieved;
// gets info about server
host = gethostbyname(params.hvalue.c_str());
if(host == NULL) {
printErr(ERR_HOSTNAME);
return ERR_HOSTNAME;
}
// makes a socket
if((clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == -1) {
printErr(ERR_SOCKET);
return ERR_SOCKET;
}
socketHelper.sin_family = AF_INET;
socketHelper.sin_port = htons(params.port);
memcpy(&(socketHelper.sin_addr), host->h_addr, host->h_length);
// connects the socket
if(connect(clientSocket, (sockaddr *)&socketHelper, sizeof(socketHelper)) == -1) {
printErr(ERR_CONNECTION);
return ERR_CONNECTION;
}
// sends data
if((size = write(clientSocket, request.c_str(), request.length())) == -1) {
printErr(ERR_SEND);
return ERR_SEND;
}
// recieves data
while ((size = read(clientSocket, buf, BUFFER_LEN)) != 0) {
recieved.erase();
recieved.append(buf, size);
data = data + recieved;
}
// closes a connection
close(clientSocket);
以及来自服务器的部分代码:
while(1) {
int clientSocket = accept(GodParticle, (struct sockaddr*) &GodAddr, &clientSocketSize);
if(clientSocket == -1) {
printErr(ERR_ACCEPT);
return ERR_ACCEPT;
}
if((pid = fork()) == 0) {
while ((size = read(clientSocket, buf, BUFFER_LEN)) != 0) {
recieved.erase();
recieved.append(buf, size);
request = request + recieved;
}
parserInput(request);
getData();
parserOutput();
if((size = write(clientSocket, sendback.c_str(), sendback.length())) == -1) {
printErr(ERR_SEND);
return ERR_SEND;
}
close(clientSocket);
exit(ERR_OK);
}
}