# HG changeset patch # User František Kučera # Date 1659740043 -7200 # Node ID 290c58261df9b751dbc27f414419a99b83c128ea # Parent 86feef4b6ee61e22e96cef44039a729233c70884 template openClientSocket() diff -r 86feef4b6ee6 -r 290c58261df9 src/Socket.cpp --- a/src/Socket.cpp Sat Aug 06 00:33:40 2022 +0200 +++ b/src/Socket.cpp Sat Aug 06 00:54:03 2022 +0200 @@ -124,25 +124,28 @@ }; +template static std::shared_ptr openClientSocket(const SocketOptions& options, int socketType, int protocol) { + AddressInfos remoteAddresses = AddressInfos::getAddressInfos( + findOption(options, OPTION_HOST, true), + findOption(options, OPTION_PORT, true), + socketType, + protocol); + + return std::shared_ptr(new SocketClass(remoteAddresses)); +} + class UDPClientSocket : public Socket { private: AddressInfos remoteAddresses; +public: + UDPClientSocket(AddressInfos remoteAddresses) : remoteAddresses(remoteAddresses) { } -public: - static std::shared_ptr open(const SocketOptions& options) { - auto protocol = findOption(options, OPTION_PROTOCOL); - - AddressInfos remoteAddresses = AddressInfos::getAddressInfos( - findOption(options, OPTION_HOST, true), - findOption(options, OPTION_PORT, true), - protocol == PROTOCOL_SCTP ? SOCK_SEQPACKET : SOCK_DGRAM, - protocol == PROTOCOL_SCTP ? IPPROTO_SCTP : IPPROTO_UDP); - - return std::shared_ptr(new UDPClientSocket(remoteAddresses)); + bool sctp = findOption(options, OPTION_PROTOCOL) == PROTOCOL_SCTP; + return openClientSocket(options, sctp ? SOCK_SEQPACKET : SOCK_DGRAM, sctp ? IPPROTO_SCTP : IPPROTO_UDP); } void send(const std::string& message) override { @@ -162,18 +165,13 @@ private: AddressInfos remoteAddresses; +public: + TCPClientSocket(AddressInfos remoteAddresses) : remoteAddresses(remoteAddresses) { } -public: static std::shared_ptr open(const SocketOptions& options) { - AddressInfos remoteAddresses = AddressInfos::getAddressInfos( - findOption(options, OPTION_HOST, true), - findOption(options, OPTION_PORT, true), - SOCK_STREAM, - IPPROTO_TCP); - - return std::shared_ptr(new TCPClientSocket(remoteAddresses)); + return openClientSocket(options, SOCK_STREAM, IPPROTO_TCP); } void send(const std::string& message) override { @@ -182,6 +180,7 @@ check(::connect(s.getFD(), ai->ai_addr, ai->ai_addrlen), "connect socket"); ssize_t written = ::write(s.getFD(), message.c_str(), message.size()); if (written != message.size()) throw std::logic_error("writing to the socket failed"); + // TODO: partial writes, repeat } const std::string receive() override {