samedi 28 mars 2015

Socket programming issue, data sent on exit


I've a problem with socket programming on OS X (C++). My client can connect to the server, but when I send data, despite the send() doesn't fail, the data are sent only when the program exits.


Here is my code :


creation of the socket and connection to server in the client constructor :



ComBridge::ComBridge(std::string comManagerIP, int portNumber){
this->myComManagerIP = comManagerIP;
this->portNum = portNumber;

initComBridge();
}

ComBridge::~ComBridge(){
close(socketFD);
}

void ComBridge::initComBridge(){
/*Opening the socket*/
socketFD = socket(AF_INET, SOCK_STREAM, 0);
if (socketFD<0) {
cout<<"Error opening socket !"<<endl;
exit(1);
}

/*Defining the server address*/
bzero((char *) &server_addr, sizeof(server_addr));
server_addr.sin_family = AF_INET;
/*bcopy(myComManagerIP.c_str(),
(char *)&server_addr.sin_addr.s_addr,
myComManagerIP.size());*/
inet_pton(AF_INET,myComManagerIP.c_str(),&server_addr.sin_addr);
server_addr.sin_port = htons(portNum);

cout<<"ip server store : "<<myComManagerIP.c_str()<<endl;

cout<<"ip server in server_addr: "<<server_addr.sin_addr.s_addr<<endl;

/*Connecting to ComManager*/
int rcon = connect(socketFD, (struct sockaddr*)&server_addr, sizeof(server_addr));
cout<<"back num for connection : "<<rcon<<endl;
if (rcon<0) {
cout<<"Failed connection to ComManager !"<<endl;
}
}


And the sending and receiving methods :



void ComBridge::readMessage(){
bzero(bufferIn,256);

/*Waiting for data from socket*/
ssize_t numOfCharRecv = recv(socketFD, &bufferIn, 255,0);
//ssize_t numOfCharRecv = read(socketFD,&bufferIn,255);

if (numOfCharRecv < 0)
cout<<"ERROR reading socket"<<endl;

/*Storing the string received in a jsonDocument*/
jsonDocument.Parse(bufferIn);
cout<<"message : "<<bufferIn<<endl;
/*Notifying observers of event*/
//notify(jsonDocument);
}

void ComBridge::writeMessage(rapidjson::Document& d){
buffer = myJsonHandler.convertJsonToString(d);

cout<<buffer<<endl;

ssize_t writeRes = send(socketFD,buffer.c_str(),strlen(buffer.c_str())+1,0);
if (writeRes < 0)
cout<<"ERROR writing to socket"<<endl;
else cout<<"Message sent ! "<<writeRes<<endl;
}


Has anyone an idea of what's wrong ?


Thanks for help !


Mikael10j




Aucun commentaire:

Enregistrer un commentaire