#pragma once
#include <cstdio>
#include <cstdlib>
#include <cstring>
namespace ChatTest
{
class chat_message
{
public:
enum {header_length = 4, max_body_length = 1024};
public:
chat_message() : body_length_(0) {}
size_t length() const
{
return header_length + body_length_;
}
void body_length(size_t new_length)
{
body_length_ = new_length;
if (body_length_ > max_body_length)
body_length_ = max_body_length;
}
size_t body_length() const
{
return body_length_;
}
char* data()
{
return data_;
}
const char* data() const
{
return data_;
}
char* body()
{
return data_ + header_length;
}
const char* body() const
{
return data_ + header_length;
}
bool encode_header()
{
char header[header_length+1] = "";
sprintf(header, "%4d", body_length_);
memcpy(data_, header, header_length);
return true;
}
bool decode_header()
{
char header[header_length + 1] = "";
strncat(header, data_, header_length);
body_length_ = atoi(header);
std::cout << body_length_ << std::endl;
if (body_length_ > max_body_length)
{
body_length_ = 0;
return false;
}
return true;
}
private:
char data_[header_length + max_body_length];
size_t body_length_;
};
}
#pragma once
#include <deque>
#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/thread.hpp>
#include "my_chat_message.h"
namespace ChatTest
{
using namespace boost::asio::ip;
typedef std::deque<chat_message> chat_message_queue;
class chat_client
{
public:
chat_client(boost::asio::io_service& io, tcp::resolver::iterator endpoint_iterator)
:io_service_(io), socket_(io)
{
start_connect(endpoint_iterator);
}
void start_connect(tcp::resolver::iterator endpoint_iterator)
{
boost::asio::async_connect(socket_,
endpoint_iterator,
boost::bind(&chat_client::hand_connect, this, boost::asio::placeholders::error));
}
void write(const chat_message& msg)//投入到队列中去
{
io_service_.post(boost::bind(&chat_client::do_write, this, msg));
}
void close()
{
io_service_.post(boost::bind(&chat_client::do_close, this));
}
private:
void hand_connect(const boost::system::error_code& error)
{
if (!error)
{
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.data(), chat_message::header_length),
boost::bind(&chat_client::hand_read_header, this, boost::asio::placeholders::error));
}
else
{
//std::cout << "connect error\n" << std::endl;
}
}
void hand_read_header(const boost::system::error_code& error)
{
if (!error && read_msg_.decode_header())
{
std::cout.write(read_msg_.data(), chat_message::header_length);
//std::cout << "\nheader\n" << read_msg_.body_length() << std::endl;
boost::asio::async_read(socket_,
boost::asio::buffer(read_msg_.body(), read_msg_.body_length()/*chat_message::max_body_length长度大于实际长度时会出做*/),
boost::bind(&chat_client::hand_read_body, this, boost::asio::placeholders::error));
}
el
boost::asio学习之[六]简单聊天程序
最新推荐文章于 2021-07-30 11:53:43 发布
本文档展示了如何使用Boost.Asio库创建一个简单的聊天程序,包括客户端和服务器端的实现。通过`async_read`和`async_write`进行异步读写,实现消息的编码、解码和传输。客户端与服务器通过TCP连接,能够接收和发送消息。
摘要由CSDN通过智能技术生成