我正在尝试连接到IRC服务器(twitch.tv)。连接成功但我不知道如何正确地从服务器读取 响应。更具体地说,我在这一行中遇到了麻烦:boost::asio::read(s, boost::asio::buffer(reply, MAX_LENGTH));
。
如果我使用MAX_LENGTH
(1024),这是一个大于响应消息大小的数字,那么程序似乎不会终止。如果我使用64这样的数字,我只能读取该消息的64个字符。我可以以某种方式阅读\r\n
或其他内容吗?我该怎么做呢?
#include <boost/asio.hpp>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
try
{
char HOSTNAME[] = "irc.chat.twitch.tv";
char PORT[] = "6667";
char PASS[] = "PASS oauth:123\r\n";
char NICK[] = "NICK 123\r\n";
char USER[] = "USER 123\r\n";
const size_t MAX_LENGTH = 1024;
boost::asio::io_service io_service;
boost::asio::ip::tcp::socket s(io_service);
boost::asio::ip::tcp::resolver resolver(io_service);
boost::asio::connect(s, resolver.resolve({HOSTNAME, PORT}));
cout << "connected\n";
boost::asio::write(s, boost::asio::buffer(PASS, strlen(PASS)));
boost::asio::write(s, boost::asio::buffer(NICK, strlen(NICK)));
boost::asio::write(s, boost::asio::buffer(USER, strlen(USER)));
cout << "sent 3 messages\n";
char reply[MAX_LENGTH];
size_t reply_length = boost::asio::read(s,
boost::asio::buffer(reply, MAX_LENGTH));
// execution never reaches here
std::cout << "Reply is: ";
std::cout.write(reply, reply_length);
std::cout << "\n";
}
catch (std::exception &e)
{
std::cerr << "Exception: " << e.what() << "\n";
}
return 0;
}
答案 0 :(得分:3)
我不熟悉IRC协议,但从快速查看RFC看起来它是基于文本的。在这种情况下,我建议使用boost :: asio :: read_until作为响应。
如果您认为这符合您的问题,请记住read_until内部可能会从指定分隔符之外的传入流中读取字节。因此,在从提供的streambuf中提取数据时要特别注意(您需要使用read_until返回的值)。
查看文档: http://www.boost.org/doc/libs/1_61_0/doc/html/boost_asio/reference/read_until/overload3.html
答案 1 :(得分:1)