使用 select() 的请求/回复服务器。无法写回客户端
request/reply server using select(). Can't write back to client
我从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 %dn", errno);
exit(3);
}
if(send( i, response.data(), response.length(),0 )== 0){
fprintf(stderr, "Error sending data %dn", errno);
exit(3);
}
} //end if
我从服务器上的客户端接收所有数据。然后,我不确定问题是在服务器上写回数据还是从客户端读取数据。我认为它是从服务器写给客户端的。当我在评论中暗示时,我想我知道我在哪里出错了,但是我已经删除了此IF语句,但我仍然无法阅读客户端的任何内容。我一开始需要设置一个可写的标志吗?请让我知道您是否需要其他任何东西。抱歉,这个帖子很长。
只需写写即可。如果它返回-1/ewoldBlock,或一个表示未写入完整响应的值,则然后, ,将FD添加到WriteFDS中,并在FD变为可写时继续写入。通常,您没有任何写入FD,因为FD通常是可写的,也就是说,它们通常在插座发送缓冲区中有空间。
相关文章:
- C/C++ Linux 上的多线程服务器/客户端崩溃
- 在 1 个服务器 n 客户端套接字 C++ MFC 应用程序中更新数据的客户端
- ZMQ - 客户端服务器:客户端意外关闭,服务器如何检测到?
- C++服务器/客户端聊天程序
- Boost-Beast 异步 Web 套接字 服务器-客户端异步读写 不在控制台上写入输出
- 服务器客户端通过原始数据错误C 发送接收结构
- TCP 服务器/客户端:客户端 recv() 返回空白缓冲区
- 在使用 Poll() 的 TCP 服务器 - 客户端连接中,我是否需要手动设置事件?我从来没有到达 POLLOUT 来写
- 是否可以寻址另一个网络中的服务器/客户端套接字?(C++)
- 嗅探 QWebsocket 服务器 - 客户端通信
- C++(不是 C)中的示例服务器/客户端代码
- 如何将ZeroMQ用于多个服务器-客户端对
- 语言之间的服务器客户端首选项
- 服务器客户端程序上的QT-QFileSystemModel
- SFML网络服务器/客户端
- 服务器/客户端TCP异步(winsock)//FD_WRITE问题
- 基本服务器/客户端代码出现问题
- 将我的简单winsock服务器/客户端应用程序变形为简单的Web服务器
- C++ Winsock 服务器-客户端远程连接
- 修复:C++服务器/客户端程序:"Connection refused"