diff C++/SocketTcp.h @ 315:c9356cb38c86

Split sockets into SocketTcp and SocketUdp
author David Demelier <markand@malikania.fr>
date Mon, 02 Mar 2015 14:00:48 +0100
parents
children 4c0af1143fc4
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/C++/SocketTcp.h	Mon Mar 02 14:00:48 2015 +0100
@@ -0,0 +1,81 @@
+/*
+ * SocketTcp.h -- portable C++ socket wrappers
+ *
+ * Copyright (c) 2013, 2014 David Demelier <markand@malikania.fr>
+ *
+ * Permission to use, copy, modify, and/or distribute this software for any
+ * purpose with or without fee is hereby granted, provided that the above
+ * copyright notice and this permission notice appear in all copies.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
+ * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
+ * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
+ * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
+ * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
+ * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
+ * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
+ */
+
+#ifndef _SOCKET_TCP_NG_3_H_
+#define _SOCKET_TCP_NG_3_H_
+
+#include "Socket.h"
+
+/**
+ * @class SocketAbstractTcp
+ * @brief Base class for TCP sockets
+ */
+class SocketAbstractTcp : public Socket {
+public:
+	using Socket::Socket;
+
+	inline SocketAbstractTcp(int domain, int protocol)
+		: Socket(domain, SOCK_STREAM, protocol)
+	{
+	}
+
+	void listen(int max = 128);
+
+	inline std::string recv(unsigned count)
+	{
+		std::string result;
+
+		result.resize(count);
+		auto n = recv(const_cast<char *>(result.data()), count);
+		result.resize(n);
+
+		return result;
+	}
+
+	inline unsigned send(const std::string &data)
+	{
+		return send(data.c_str(), data.size());
+	}
+
+	virtual unsigned recv(void *data, unsigned length) = 0;
+
+	virtual unsigned send(const void *data, unsigned length) = 0;
+};
+
+/**
+ * @class SocketTcp
+ * @brief End-user class for TCP sockets
+ */
+class SocketTcp final : public SocketAbstractTcp {
+public:
+	using SocketAbstractTcp::SocketAbstractTcp;
+	using SocketAbstractTcp::recv;
+	using SocketAbstractTcp::send;
+
+	SocketTcp accept();
+
+	SocketTcp accept(SocketAddress &info);
+
+	void connect(const SocketAddress &address);
+
+	unsigned recv(void *data, unsigned length) override;
+
+	unsigned send(const void *data, unsigned length) override;
+};
+
+#endif // !_SOCKET_TCP_NG_3_H_