我正在尝试以非常基本的方式实现 irc 协议。我的第一次尝试是使用 boost::asio 并连接到服务器并读取 motd。AFAIK motd 在连接时发送给每个客户端。我已经制作了以下测试程序,它似乎没有做任何事情。这不是一段很好的代码,但这就是我在几个令人沮丧的小时后所拥有的一切。
#define _WIN32_WINNT 0x0501
#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>
#include <boost/function.hpp>
#include <queue>
class IrcConnection
{
public:
IrcConnection(const std::string& server, int port, boost::function<void (const std::string&)> onMessage, boost::asio::io_service& io_service): s(server), p(port), onM(onMessage), ios(io_service), socket(io_service)
{
}
void connect()
{
somethingHappened = false;
//DNS stuff
boost::asio::ip::tcp::resolver resolver(ios);
boost::asio::ip::tcp::resolver::query query(s , "0");
boost::asio::ip::tcp::resolver::iterator iter = resolver.resolve(query);
boost::asio::ip::tcp::resolver::iterator end;
boost::system::error_code error;
while(iter != end)
{
boost::asio::ip::tcp::endpoint endpoint = iter->endpoint();
endpoint.port(p);
socket.close();
socket.connect(endpoint, error);
iter++;
}
if(error)
{
std::cout << "ERROR" << std::endl;
std::cout << error << std::endl;
}
std::cout << "Connected to: " << socket.remote_endpoint().address().to_string() << std::endl;
//read from the socket until a space is found
boost::asio::async_read_until(socket, currentData, ' ', boost::bind(&IrcConnection::onReceiveFinished, this, boost::asio::placeholders::error));
}
void disconnect()
{
socket.close();
}
void send(int priority, const std::string& message)
{
}
bool somethingHappened;
private:
std::string s;
int p;
boost::function<void (const std::string&)> onM;
boost::asio::io_service& ios;
boost::asio::ip::tcp::socket socket;
std::priority_queue<std::string> outQueue;
boost::asio::streambuf currentData;
void onReceiveFinished(const boost::system::error_code& error)
{
if(error)
{
disconnect();
std::cout << "ERRORRRR" << std::endl;
std::cout << error << std::endl;
}
std::cout << "STUFF IS OCCURING" << std::endl;
somethingHappened = true;
std::istream stream(¤tData);
std::string data;
std::getline(stream, data);
boost::asio::async_read_until(socket, currentData, ' ', boost::bind(&IrcConnection::onReceiveFinished, this, boost::asio::placeholders::error));
ios.dispatch(boost::bind(onM, data));
}
};
void onMe(const std::string& x)
{
std::cout << "MESSAGE" << std::endl;
std::cout << x << std::endl;
}
int main()
{
boost::asio::io_service ios;
std::string server = "irc.efnet.org";
int port = 6667;
IrcConnection x(server, port, onMe, ios);
x.connect();
while(!x.somethingHappened)
{
//
}
return 0;
}
该程序尝试连接到 irc.efnet.org 并读取,直到发送一个空间,然后将该数据吐出到终端。但是我运行它,打印的只是我连接的 IP 地址,然后程序不会终止。
我需要做什么来获得我的缩进行为?