st_asio_wrapper_udp_socket.h 8.2 KB
Newer Older
1 2 3 4 5
/*
 * st_asio_wrapper_udp_socket.h
 *
 *  Created on: 2012-3-2
 *      Author: youngwolf
6 7 8
 *		email: mail2tao@163.com
 *		QQ: 676218192
 *		Community on QQ: 198941541
9 10 11 12 13 14 15 16 17
 *
 * this class used at both client and server endpoint
 */

#ifndef ST_ASIO_WRAPPER_UDP_SOCKET_H_
#define ST_ASIO_WRAPPER_UDP_SOCKET_H_

#include <boost/array.hpp>

Y
youngwolf 已提交
18
#include "st_asio_wrapper_socket.h"
Y
youngwolf 已提交
19
#include "st_asio_wrapper_unpacker.h"
20

Y
youngowlf 已提交
21 22
//in set_local_addr, if the IP is empty, UDP_DEFAULT_IP_VERSION will define the IP version,
//or, the IP version will be deduced by the IP address.
Y
youngwolf 已提交
23
//boost::asio::ip::udp::v4() means ipv4 and boost::asio::ip::udp::v6() means ipv6.
24
#ifndef UDP_DEFAULT_IP_VERSION
Y
youngwolf 已提交
25
#define UDP_DEFAULT_IP_VERSION boost::asio::ip::udp::v4()
26 27
#endif

Y
youngwolf 已提交
28 29 30 31
#ifndef DEFAULT_UDP_UNPACKER
#define DEFAULT_UDP_UNPACKER udp_unpacker
#endif

32 33
namespace st_asio_wrapper
{
Y
youngwolf 已提交
34 35
namespace st_udp
{
36

Y
youngwolf 已提交
37
template <typename Packer = DEFAULT_PACKER, typename Unpacker = DEFAULT_UDP_UNPACKER, typename Socket = boost::asio::ip::udp::socket>
38
class st_udp_socket_base : public st_socket<Socket, Packer, Unpacker, udp_msg<typename Packer::msg_type>, udp_msg<typename Unpacker::msg_type>>
Y
youngwolf 已提交
39
{
40
public:
41 42 43 44
	typedef udp_msg<typename Packer::msg_type> in_msg_type;
	typedef const in_msg_type in_msg_ctype;
	typedef udp_msg<typename Unpacker::msg_type> out_msg_type;
	typedef const out_msg_type out_msg_ctype;
Y
youngwolf 已提交
45 46

public:
47 48
	st_udp_socket_base(boost::asio::io_service& io_service_) : st_socket<Socket, Packer, Unpacker, in_msg_type, out_msg_type>(io_service_), unpacker_(boost::make_shared<Unpacker>())
		{ST_THIS reset_state();}
49 50

	//reset all, be ensure that there's no any operations performed on this st_udp_socket when invoke it
51
	//please note, when reuse this st_udp_socket, st_object_pool will invoke reset(), child must re-write this to initialize
Y
youngowlf 已提交
52
	//all member variables, and then do not forget to invoke st_udp_socket::reset() to initialize father's
53
	//member variables
54 55
	virtual void reset()
	{
Y
youngwolf 已提交
56 57
		ST_THIS reset_state();
		ST_THIS clear_buffer();
58

Y
youngwolf 已提交
59
		boost::system::error_code ec;
Y
youngwolf 已提交
60 61
		ST_THIS lowest_layer().close(ec);
		ST_THIS lowest_layer().open(local_addr.protocol(), ec); assert(!ec);
62
#ifndef NOT_REUSE_ADDRESS
Y
youngwolf 已提交
63
		ST_THIS lowest_layer().set_option(boost::asio::socket_base::reuse_address(true), ec); assert(!ec);
64
#endif
Y
youngwolf 已提交
65
		ST_THIS lowest_layer().bind(local_addr, ec); assert(!ec);
66 67
		if (ec)
			unified_out::error_out("bind failed.");
68 69
	}

70
	bool set_local_addr(unsigned short port, const std::string& ip = std::string())
71
	{
72
		if (ip.empty())
Y
youngwolf 已提交
73
			local_addr = boost::asio::ip::udp::endpoint(UDP_DEFAULT_IP_VERSION, port);
74 75
		else
		{
76 77 78 79 80 81
			boost::system::error_code ec;
			auto addr = boost::asio::ip::address::from_string(ip, ec);
			if (ec)
				return false;

			local_addr = boost::asio::ip::udp::endpoint(addr, port);
82
		}
83 84

		return true;
85
	}
Y
youngwolf 已提交
86
	const boost::asio::ip::udp::endpoint& get_local_addr() const {return local_addr;}
87

88 89 90 91
	void disconnect() {force_close();}
	void force_close() {clean_up();}
	void graceful_close() {clean_up();}

Y
youngwolf 已提交
92
	//get or change the unpacker at runtime
93
	//changing unpacker at runtime is not thread-safe, this operation can only be done in on_msg(), reset() or constructor, please pay special attention
94
	//we can resolve this defect via mutex, but i think it's not worth, because this feature is not frequently used
95 96 97
	boost::shared_ptr<i_udp_unpacker<typename Packer::msg_type>> inner_unpacker() {return unpacker_;}
	boost::shared_ptr<const i_udp_unpacker<typename Packer::msg_type>> inner_unpacker() const {return unpacker_;}
	void inner_unpacker(const boost::shared_ptr<i_udp_unpacker<typename Packer::msg_type>>& _unpacker_) {unpacker_ = _unpacker_;}
98

99
	using st_socket<Socket, Packer, Unpacker, in_msg_type, out_msg_type>::send_msg;
100 101
	///////////////////////////////////////////////////
	//msg sending interface
Y
youngwolf 已提交
102 103 104 105 106 107
	UDP_SEND_MSG(send_msg, false) //use the packer with native = false to pack the msgs
	UDP_SEND_MSG(send_native_msg, true) //use the packer with native = true to pack the msgs
	//guarantee send msg successfully even if can_overflow equal to false
	//success at here just means put the msg into st_udp_socket's send buffer
	UDP_SAFE_SEND_MSG(safe_send_msg, send_msg)
	UDP_SAFE_SEND_MSG(safe_send_native_msg, send_native_msg)
Y
youngwolf 已提交
108 109 110
	//like safe_send_msg and safe_send_native_msg, but non-block
	UDP_POST_MSG(post_msg, false)
	UDP_POST_MSG(post_native_msg, true)
111 112 113
	//msg sending interface
	///////////////////////////////////////////////////

114
	void show_info(const char* head, const char* tail) const {unified_out::info_out("%s %s:%hu %s", head, local_addr.address().to_string().c_str(), local_addr.port(), tail);}
115

116
protected:
117 118
	virtual bool do_start()
	{
Y
youngwolf 已提交
119
		if (!ST_THIS get_io_service().stopped())
120
		{
Y
youngwolf 已提交
121
			ST_THIS next_layer().async_receive_from(unpacker_->prepare_next_recv(), peer_addr,
122
				boost::bind(&st_udp_socket_base::recv_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
123 124 125 126 127 128 129 130 131 132

			return true;
		}

		return false;
	}

	//must mutex send_msg_buffer before invoke this function
	virtual bool do_send_msg()
	{
Y
youngwolf 已提交
133 134
		if (!is_send_allowed() || ST_THIS get_io_service().stopped())
			ST_THIS sending = false;
135
		else if (!ST_THIS sending && !ST_THIS send_msg_buffer.empty())
136
		{
Y
youngwolf 已提交
137
			ST_THIS sending = true;
138
			ST_THIS last_send_msg.swap(ST_THIS send_msg_buffer.front());
Y
youngwolf 已提交
139
			ST_THIS next_layer().async_send_to(boost::asio::buffer(ST_THIS last_send_msg.data(), ST_THIS last_send_msg.size()), ST_THIS last_send_msg.peer_addr,
140
				boost::bind(&st_udp_socket_base::send_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
141
			ST_THIS send_msg_buffer.pop_front();
142 143
		}

Y
youngwolf 已提交
144
		return ST_THIS sending;
145 146
	}

147
	virtual bool is_send_allowed() const {return ST_THIS lowest_layer().is_open() && st_socket<Socket, Packer, Unpacker, in_msg_type, out_msg_type>::is_send_allowed();}
148 149
	//can send data or not(just put into send buffer)

Y
youngwolf 已提交
150
	virtual void on_recv_error(const boost::system::error_code& ec)
151 152
	{
		if (boost::asio::error::operation_aborted != ec)
153
			unified_out::error_out("recv msg error (%d %s)", ec.value(), ec.message().data());
154
	}
155 156

#ifndef FORCE_TO_USE_MSG_RECV_BUFFER
157
	virtual bool on_msg(out_msg_type& msg) {unified_out::debug_out("recv(" size_t_format "): %s", msg.size(), msg.data()); return true;}
158 159
#endif

160
	virtual bool on_msg_handle(out_msg_type& msg, bool link_down) {unified_out::debug_out("recv(" size_t_format "): %s", msg.size(), msg.data()); return true;}
161 162 163

	void clean_up()
	{
Y
youngwolf 已提交
164
		if (ST_THIS lowest_layer().is_open())
165
		{
Y
youngwolf 已提交
166
			boost::system::error_code ec;
Y
youngwolf 已提交
167 168
			ST_THIS lowest_layer().shutdown(boost::asio::ip::udp::socket::shutdown_both, ec);
			ST_THIS lowest_layer().close(ec);
169 170
		}

Y
youngwolf 已提交
171 172
		ST_THIS stop_all_timer();
		ST_THIS reset_state();
173 174
	}

Y
youngwolf 已提交
175
	void recv_handler(const boost::system::error_code& ec, size_t bytes_transferred)
176 177 178
	{
		if (!ec && bytes_transferred > 0)
		{
179 180
			ST_THIS temp_msg_buffer.resize(ST_THIS temp_msg_buffer.size() + 1);
			ST_THIS temp_msg_buffer.back().swap(peer_addr, unpacker_->parse_msg(bytes_transferred));
Y
youngwolf 已提交
181
			ST_THIS dispatch_msg();
182 183
		}
#ifdef _MSC_VER
184
		else if (boost::asio::error::connection_refused == ec || boost::asio::error::connection_reset == ec)
185
			do_start();
186 187 188 189 190
#endif
		else
			on_recv_error(ec);
	}

Y
youngwolf 已提交
191
	void send_handler(const boost::system::error_code& ec, size_t bytes_transferred)
192 193 194 195 196
	{
		if (!ec)
		{
			assert(bytes_transferred > 0);
#ifdef WANT_MSG_SEND_NOTIFY
197
			ST_THIS on_msg_send(ST_THIS last_send_msg);
198 199 200
#endif
		}
		else
Y
youngwolf 已提交
201
			ST_THIS on_send_error(ec);
202

203
		boost::unique_lock<boost::shared_mutex> lock(ST_THIS send_msg_buffer_mutex);
Y
youngwolf 已提交
204
		ST_THIS sending = false;
Y
youngwolf 已提交
205

206
		//send msg sequentially, that means second send only after first send success
207
		//under windows, send a msg to addr_any may cause sending errors, please note
Y
youngowlf 已提交
208
		//for UDP in st_asio_wrapper, sending error will not stop the following sending.
209
#ifdef WANT_ALL_MSG_SEND_NOTIFY
210
		if (!do_send_msg())
211
			ST_THIS on_all_msg_send(ST_THIS last_send_msg);
212 213
#else
		do_send_msg();
214
#endif
215 216 217

		if (!ST_THIS sending)
			ST_THIS last_send_msg.clear();
218 219 220
	}

protected:
221
	boost::shared_ptr<i_udp_unpacker<typename Packer::msg_type>> unpacker_;
Y
youngwolf 已提交
222
	boost::asio::ip::udp::endpoint peer_addr, local_addr;
223
};
Y
youngwolf 已提交
224
typedef st_udp_socket_base<> st_udp_socket;
225

Y
youngwolf 已提交
226 227 228
} //namespace st_udp
} //namespace st_asio_wrapper

229
using namespace st_asio_wrapper::st_udp; //compatible with old version which doesn't have st_udp namespace.
230 231

#endif /* ST_ASIO_WRAPPER_UDP_SOCKET_H_ */