#include "stdafx.h"
#include "UDPSocket.h"
UDPSocket::UDPSocket() {
Create(SOCK_DGRAM);
CSockAddr adr(INADDR_ANY, 0);
Bind(adr);
}
int UDPSocket::init(const string & host, int port){
CSockAddr s(host.c_str(), port);
try {
server = GetHostByName(host.c_str(), port);
return 1;
}
catch (CBlockingSocketException * e){
e->print();
return 0;
}
catch (...) {
cerr << "Could not determine hostname." << endl;
return 0;
}
}
int UDPSocket::receiveMessageBlock(string & buf){
try {
int x = ReceiveDatagram(tempBuf, tempBufSize, server,1);
tempBuf[x] = '\0';
buf = tempBuf;
cerr << "Received:" << endl << buf << endl;
return 1;
}
catch (CBlockingSocketException * e){
e->print();
return 0;
}
catch (...) {
cerr << "Could not receive message. Is server running?" << endl;
return 0;
}
}
int UDPSocket::sendMessage(const string & buf){
try {
cerr << "Sending:" << endl << buf << endl;
SendDatagram(buf.c_str(), buf.size(), server, 1);
}
catch (CBlockingSocketException * e){
e->print();
return 0;
}
catch (...) {
cerr << "Could not send message. Is server running?" << endl;
return 0;
}
return 1;
}