我从beej 指南中获得了所有这些代码,因此可以从那里看到所有接受。在 Beej 的代码中,他从客户端获取消息,然后将消息发送给所有其他客户端。这可以从这里的这个片段中看出:
// handle data from a client
if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
//handle error
}
}
else {
// we got some data from a client
for(j = 0; j <= fdmax; j++) {
// send to everyone!
if (FD_ISSET(j, &master)) {
// except the listener and ourselves
if (j != listener && j != i) {
if (send(j, buf, nbytes, 0) == -1) {
perror("send");
}
}
}
}
}
} // END handle data from client
我不想将相同的消息发送给所有客户端,而是将其调整为请求/回复功能,并向我收到数据的同一客户端发送回复。
这是我到目前为止所拥有的:
long length = 0;
string stringRead;
messagebroker broker;
read( i, &length, sizeof( length ) );
length = ntohl( length );
if(length > -1)
while ( 0 < length ) {
char buffer[1024];
int cread;
cread = read( i, buffer, min( sizeof( buffer ), length ) );
stringRead.append( buffer, cread );
length -= cread;
}
cout << "Got Message: " + stringRead << endl;
string response = broker.handleMessage(stringRead.c_str());
cout << "sending response" << response << endl;
//socket ready for writing
if (FD_ISSET(i, &master)) { //should i check to see if write_fds? I have this here
//simply because the guide has it, but i am suspicious
//it is there so we can not write to the master.
length = htonl( response.length() );
cout << "sent length" << endl;
if(send( i, &length, sizeof(length) , 0) == 0){
fprintf(stderr, "Error sending data %d\n", errno);
exit(3);
}
if(send( i, response.data(), response.length(),0 )== 0){
fprintf(stderr, "Error sending data %d\n", errno);
exit(3);
}
} //end if
我从服务器上的客户端接收所有数据。然后我不确定问题是在服务器上写回数据,还是从客户端读取。我假设它正在从服务器写入客户端。正如我在评论中暗示的那样,我想我知道我哪里出错了,但是我已经删除了这个 if 语句,我仍然无法在客户端读取任何内容。我需要在一开始就设置一个可写标志吗?如果您需要其他任何东西,请告诉我。抱歉这篇文章太长了。