我有一个服务器多客户端程序。服务器需要(并且可以)随时向客户端发送消息,因此客户端需要不断准备好接收(并在其控制台上显示)服务器发送的所有消息。
同时,客户端控制台需要接受输入发送到服务器进行处理(服务器充当客户端之间的中介)。
我怎样才能做到这一点?我正在使用取自http://www.codeproject.com/Articles/7785/Single-Server-With-Multiple-Clients-a-Simple-C-Imp的一段代码和客户端代码(我附上下面)通过接受来自服务器的消息,在它准备好接收消息之前将其发送到服务器来工作。我如何调整它来做我需要的?
我只包括客户端代码的主体,因为我认为这可能只是使用循环的问题——尽管我不知道是什么循环——所以如果我应该附加任何其他代码,请告诉我。
#include "stdafx.h"
#include "mySocket.h"
#include "myLog.h"
#include "myException.h"
#include "myHostInfo.h"
myLog winLog;
void readServerConfig(string&);
void checkFileExistence(const string&);
int main()
{
//initialize the winsock library
myTcpSocket::initialize();
//get client's information (assume neither the name nor the address is given)
winLog << endl;
winLog << "retrieve the localHost [CLIENT] name and address:" << endl;
myHostInfo clientInfo;
string clientName = clientInfo.getHostName();
string clientIPAddress = clientInfo.getHostIPAddress();
cout << "name: " << clientName << endl;
cout << "address: " << clientIPAddress << endl;
winLog << " ==> name: " << clientName << endl;
winLog << " ==> address: " << clientIPAddress << endl;
//get server's IP address and name
string serverIPAddress = "";
readServerConfig(serverIPAddress);
winLog << endl;
winLog << "retrieve the remoteHost [SERVER] name and address:" << endl;
winLog << " ==> the given address is " << serverIPAddress << endl;
myHostInfo serverInfo(serverIPAddress,ADDRESS);
string serverName = serverInfo.getHostName();
cout << "name: " << serverName << endl;
cout << "address: " << serverIPAddress << endl;
winLog << " ==> name: " << serverName << endl;
winLog << " ==> address: " << serverIPAddress << endl;
//create the socket for client
myTcpSocket myClient(PORTNUM);
cout << myClient;
winLog << "client configuation: " << endl;
winLog << myClient;
// connect to the server.
cout << "connecting to the server [" << serverName << "] ... " << endl;
winLog << "connecting to the server [" << serverName << "] ... " << endl;
myClient.connectToServer(serverIPAddress, ADDRESS);
int recvBytes = 0;
while (1)
{
// send message to server
char messageToServer[MAX_MSG_LEN+1];
memset(messageToServer, 0, sizeof(messageToServer));
cout << "[SEND] ";
cin.getline(messageToServer,MAX_MSG_LEN);
winLog << "[SEND] " << messageToServer << endl;
myClient.sendMessage(string(messageToServer));
if ( !string(messageToServer).compare("Quit") || !string(messageToServer).compare("quit") )
break;
// receive message from server
/* string messageFromServer = "";
recvBytes = myClient.receiveMessage(messageFromServer);
if ( recvBytes == -99 ) break;
cout << "[RECV:" << serverName << "]: " << messageFromServer << endl;
winLog << "[RECV:" << serverName << "]: " << messageFromServer << endl;*/
}
return 1;
}