// UDPSocket.cpp: implementation of the UDPSocket class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "UDPSocket.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

/** Create a UDPSocket. */
UDPSocket::UDPSocket() {
	Create(SOCK_DGRAM);
	CSockAddr adr(INADDR_ANY, 0);
	Bind(adr);
}


/** Set the server name (the one we will be talking to) and port */
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;
	}
}

/** Get a message from the server. This call will block until there
	is a message to get. The message will be in buf. */
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;
	}
}

/** Send message buf to the server */

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;
}