-
Notifications
You must be signed in to change notification settings - Fork 0
Communications
pabramsor edited this page Jun 21, 2014
·
9 revisions
Socket class has a static member function to create socket classes (It is only possible to create these socket without this function due to security). These classes are completely "Ready to use", which means that can be use instantly after its creating.
Here is an example of TCP server use and it's other side client.
#include <core/comm/Socket.h>
#include <iostream>
using namespace BOViL::comm;
int main(void){
Socket *socket = Socket::createSocket(eSocketType::serverTCP, "2048");
std::string msg = "";
do{
msg.clear();
socket->receiveMsg(msg);
std::cout << "Received: " << msg << std::endl;
}while(std::strcmp(msg.c_str(), "QUIT"));
delete socket;
return 0;
}
#include <core/comm/Socket.h>
#include <iostream>
using namespace BOViL::comm;
int testSocketClient(std::string _ip, std::string _port){
Socket *socket = Socket::createSocket(eSocketType::clientTCP, "2048", "localhost");
std::string msg = "Hello world";
do {
std::cin >> msg;
std::cout << "Send: " << msg << std::endl;
socket->sendMsg(msg);
} while(std::strcmp(msg.c_str(), "QUIT"));
delete socket;
return 0;
}
If multi-threading is needed read the following section.
In case of a server that accept multiple connection here is the example code:
#include <core/comm/ServerMultiThreadTCP.h>
#include <vector>
#include <map>
#include <iostream>
int main(int _argc, char** _argv){
std::map<std::string, std::string> hashMap = parseArgs(_argc, _argv);
BOViL::comm::ServerMultiThreadTCP server(hashMap["PORT"]);
bool run = true;
while(run){
int noConn = server.requestNoConnections();
for(int i = 0 ; i < noConn ; i++){
std::vector<std::string> msgs;
if(server.readMsgsFrom(msgs, i)){
for(unsigned int j = 0 ; j < msgs.size() ; j++){
std::cout << "Data from thread " << i << ": " << msgs[j] << std::endl;
}
}
}
}
system("PAUSE");
return 0;
}
Clients are the same