st_asio_wrapper_udp_socket.h 8.7 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
 *
 * this class used at both client and server endpoint
 */

#ifndef ST_ASIO_WRAPPER_UDP_SOCKET_H_
#define ST_ASIO_WRAPPER_UDP_SOCKET_H_

Y
youngwolf 已提交
16
#include "st_asio_wrapper_socket.h"
17

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

namespace st_asio_wrapper
{

28
template <typename Packer, typename Unpacker, typename Socket = boost::asio::ip::udp::socket>
29
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 已提交
30
{
31 32 33
protected:
	typedef st_socket<Socket, Packer, Unpacker, udp_msg<typename Packer::msg_type>, udp_msg<typename Unpacker::msg_type>> super;

34
public:
35 36 37 38
	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 已提交
39 40

public:
41 42
	using super::TIMER_BEGIN;
	using super::TIMER_END;
43

44
	st_udp_socket_base(boost::asio::io_service& io_service_) : super(io_service_), unpacker_(boost::make_shared<Unpacker>()) {}
45 46

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

Y
youngwolf 已提交
55
		boost::system::error_code ec;
Y
youngwolf 已提交
56
		ST_THIS lowest_layer().open(local_addr.protocol(), ec); assert(!ec);
Y
youngwolf 已提交
57
#ifndef ST_ASIO_NOT_REUSE_ADDRESS
Y
youngwolf 已提交
58
		ST_THIS lowest_layer().set_option(boost::asio::socket_base::reuse_address(true), ec); assert(!ec);
59
#endif
Y
youngwolf 已提交
60
		ST_THIS lowest_layer().bind(local_addr, ec); assert(!ec);
61 62
		if (ec)
			unified_out::error_out("bind failed.");
63
	}
Y
youngwolf 已提交
64

65 66
	void reset_state()
	{
67
		unpacker_->reset_state();
68
		super::reset_state();
69 70
	}

71
	bool set_local_addr(unsigned short port, const std::string& ip = std::string())
72
	{
73
		if (ip.empty())
Y
youngwolf 已提交
74
			local_addr = boost::asio::ip::udp::endpoint(ST_ASIO_UDP_DEFAULT_IP_VERSION, port);
75 76
		else
		{
77 78 79 80 81 82
			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);
83
		}
84 85

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

89
	void disconnect() {force_close();}
90
	void force_close() {show_info("link:", "been closed."); do_close();}
91
	void graceful_close() {force_close();}
92

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

100
	using super::send_msg;
101 102
	///////////////////////////////////////////////////
	//msg sending interface
Y
youngwolf 已提交
103 104 105 106 107 108
	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 已提交
109 110 111
	//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)
112 113 114
	//msg sending interface
	///////////////////////////////////////////////////

115
	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);}
116

117
protected:
118 119
	virtual bool do_start()
	{
120
		if (!ST_THIS stopped())
121
		{
122
			do_recv_msg();
123 124 125 126 127 128 129 130 131
			return true;
		}

		return false;
	}

	//must mutex send_msg_buffer before invoke this function
	virtual bool do_send_msg()
	{
132
		if (!is_send_allowed() || ST_THIS stopped())
Y
youngwolf 已提交
133
			ST_THIS sending = false;
134
		else if (!ST_THIS sending && !ST_THIS send_msg_buffer.empty())
135
		{
Y
youngwolf 已提交
136
			ST_THIS sending = true;
137 138
			ST_THIS stat.send_delay_sum += super::statistic::local_time() - ST_THIS send_msg_buffer.front().begin_time;
			ST_THIS send_msg_buffer.front().swap(last_send_msg);
139 140
			ST_THIS send_msg_buffer.pop_front();

141
			boost::shared_lock<boost::shared_mutex> lock(close_mutex);
142 143
			last_send_msg.restart();
			ST_THIS next_layer().async_send_to(boost::asio::buffer(last_send_msg.data(), last_send_msg.size()), last_send_msg.peer_addr,
Y
youngwolf 已提交
144
				ST_THIS make_handler_error_size(boost::bind(&st_udp_socket_base::send_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)));
145 146
		}

Y
youngwolf 已提交
147
		return ST_THIS sending;
148 149
	}

150 151
	virtual void do_recv_msg()
	{
152 153 154
		auto recv_buff = unpacker_->prepare_next_recv();
		assert(boost::asio::buffer_size(recv_buff) > 0);

155
		boost::shared_lock<boost::shared_mutex> lock(close_mutex);
156
		ST_THIS next_layer().async_receive_from(recv_buff, peer_addr,
Y
youngwolf 已提交
157
			ST_THIS make_handler_error_size(boost::bind(&st_udp_socket_base::recv_handler, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred)));
158 159
	}

160
	virtual bool is_send_allowed() const {return ST_THIS lowest_layer().is_open() && super::is_send_allowed();}
161 162
	//can send data or not(just put into send buffer)

Y
youngwolf 已提交
163
	virtual void on_recv_error(const boost::system::error_code& ec)
164 165
	{
		if (boost::asio::error::operation_aborted != ec)
166
			unified_out::error_out("recv msg error (%d %s)", ec.value(), ec.message().data());
167
	}
168

Y
youngwolf 已提交
169 170
#ifndef ST_ASIO_FORCE_TO_USE_MSG_RECV_BUFFER
	virtual bool on_msg(out_msg_type& msg) {unified_out::debug_out("recv(" ST_ASIO_SF "): %s", msg.size(), msg.data()); return true;}
171 172
#endif

Y
youngwolf 已提交
173
	virtual bool on_msg_handle(out_msg_type& msg, bool link_down) {unified_out::debug_out("recv(" ST_ASIO_SF "): %s", msg.size(), msg.data()); return true;}
174

175
	void do_close()
176
	{
177
		ST_THIS stop_all_timer();
178 179
		ST_THIS started_ = false;
//		ST_THIS reset_state();
180

Y
youngwolf 已提交
181
		if (ST_THIS lowest_layer().is_open())
182
		{
Y
youngwolf 已提交
183
			boost::system::error_code ec;
Y
youngwolf 已提交
184
			ST_THIS lowest_layer().shutdown(boost::asio::ip::udp::socket::shutdown_both, ec);
185

186
			boost::unique_lock<boost::shared_mutex> lock(close_mutex);
Y
youngwolf 已提交
187
			ST_THIS lowest_layer().close(ec);
188 189 190
		}
	}

Y
youngwolf 已提交
191
private:
Y
youngwolf 已提交
192
	void recv_handler(const boost::system::error_code& ec, size_t bytes_transferred)
193 194 195
	{
		if (!ec && bytes_transferred > 0)
		{
196 197
			++ST_THIS stat.recv_msg_sum;
			ST_THIS stat.recv_byte_sum += bytes_transferred;
198 199
			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 已提交
200
			ST_THIS dispatch_msg();
201 202
		}
#ifdef _MSC_VER
203
		else if (boost::asio::error::connection_refused == ec || boost::asio::error::connection_reset == ec)
204
			do_start();
205 206 207 208 209
#endif
		else
			on_recv_error(ec);
	}

Y
youngwolf 已提交
210
	void send_handler(const boost::system::error_code& ec, size_t bytes_transferred)
211 212 213
	{
		if (!ec)
		{
214
			assert(bytes_transferred == last_send_msg.size());
215

216
			ST_THIS stat.send_time_sum += super::statistic::local_time() - last_send_msg.begin_time;
217 218
			ST_THIS stat.send_byte_sum += bytes_transferred;
			++ST_THIS stat.send_msg_sum;
Y
youngwolf 已提交
219
#ifdef ST_ASIO_WANT_MSG_SEND_NOTIFY
220
			ST_THIS on_msg_send(last_send_msg);
221 222 223
#endif
		}
		else
Y
youngwolf 已提交
224
			ST_THIS on_send_error(ec);
225

226
		boost::unique_lock<boost::shared_mutex> lock(ST_THIS send_msg_buffer_mutex);
Y
youngwolf 已提交
227
		ST_THIS sending = false;
Y
youngwolf 已提交
228

229
		//send msg sequentially, that means second send only after first send success
230
		//under windows, send a msg to addr_any may cause sending errors, please note
Y
youngowlf 已提交
231
		//for UDP in st_asio_wrapper, sending error will not stop the following sending.
Y
youngwolf 已提交
232
#ifdef ST_ASIO_WANT_ALL_MSG_SEND_NOTIFY
233
		if (!do_send_msg())
234
			ST_THIS on_all_msg_send(last_send_msg);
235 236
#else
		do_send_msg();
237
#endif
238 239

		if (!ST_THIS sending)
240
			last_send_msg.clear();
241 242 243
	}

protected:
244 245
	typename super::in_msg last_send_msg;
	boost::shared_ptr<i_udp_unpacker<typename Packer::msg_type>> unpacker_;
Y
youngwolf 已提交
246
	boost::asio::ip::udp::endpoint peer_addr, local_addr;
247 248

	boost::shared_mutex close_mutex;
249
};
Y
youngwolf 已提交
250

251
} //namespace
252 253

#endif /* ST_ASIO_WRAPPER_UDP_SOCKET_H_ */