Index   Main   Namespaces   Classes   Hierarchy   Annotated   Files   Compound   Global   Pages  

SgGtpClient.cpp

Go to the documentation of this file.
00001 //----------------------------------------------------------------------------
00002 /** @file SgGtpClient.cpp
00003     See SgGtpClient.h
00004 */
00005 //----------------------------------------------------------------------------
00006 
00007 #include "SgSystem.h"
00008 #include "SgGtpClient.h"
00009 
00010 #include <sstream>
00011 #include "SgDebug.h"
00012 
00013 using namespace std;
00014 
00015 //----------------------------------------------------------------------------
00016 
00017 SgGtpFailure::SgGtpFailure(const std::string& message)
00018     : SgException(message)
00019 {
00020 }
00021 
00022 //----------------------------------------------------------------------------
00023 
00024 SgGtpClient::SgGtpClient(istream& in, ostream& out, bool verbose)
00025     : m_verbose(verbose),
00026       m_in(in),
00027       m_out(out)
00028 {
00029 }
00030 
00031 SgGtpClient::~SgGtpClient()
00032 {
00033 }
00034 
00035 string SgGtpClient::Send(const string& command)
00036 {
00037     m_out << command << '\n';
00038     m_out.flush();
00039     if (m_verbose)
00040         SgDebug() << "<< " << command << '\n';
00041     if (! m_out)
00042         throw SgGtpFailure("GTP write connection is broken");
00043     ostringstream response;
00044     bool done = false;
00045     bool isFirst = true;
00046     bool success = true;
00047     while (! done)
00048     {
00049         string line;
00050         getline(m_in, line);
00051         if (! m_in)
00052             throw SgGtpFailure("GTP read connection is broken");
00053         if (m_verbose)
00054             SgDebug() << ">> " << line << '\n';
00055         if (isFirst)
00056         {
00057             if (line.size() < 2 || (line[0] != '=' && line[0] != '?')
00058                 || line[1] != ' ')
00059                 throw SgGtpFailure("Invalid response: '" + line + "'");
00060             if (line[0] == '?')
00061                 success = false;
00062             line = line.substr(2);
00063             response << line;
00064             isFirst = false;
00065         }
00066         else
00067         {
00068             if (line.empty())
00069                 done = true;
00070             else
00071                 response << '\n' << line;
00072         }
00073     }
00074     if (! success)
00075         throw SgGtpFailure(response.str());
00076     return response.str();
00077 }
00078 
00079 //----------------------------------------------------------------------------


17 Jun 2010 Doxygen 1.4.7