Created
November 2, 2014 02:27
-
-
Save m-mizutani/d82f0245349a9dc8570a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <unistd.h> | |
#include <stdio.h> | |
#include <sys/types.h> | |
#include <sys/socket.h> | |
#include <netinet/in.h> | |
#include <arpa/inet.h> | |
#include <netdb.h> | |
#include <exception> | |
#include <string> | |
int connect_tcp(std::string host, std::string port) { | |
struct addrinfo hints; | |
struct addrinfo *result, *rp; | |
int sock; | |
int r; | |
memset(&hints, 0, sizeof(struct addrinfo)); | |
hints.ai_family = AF_UNSPEC; | |
hints.ai_socktype = SOCK_STREAM; | |
hints.ai_flags = 0; | |
hints.ai_protocol = 0; | |
if (0 != (r = getaddrinfo(host.c_str(), port.c_str(), | |
&hints, &result))) { | |
std::string errmsg(gai_strerror(r)); | |
throw std::runtime_error("getaddrinfo error: " + errmsg); | |
} | |
for (rp = result; rp != NULL; rp = rp->ai_next) { | |
sock = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol); | |
if (sock == -1) { | |
continue; | |
} | |
if (connect(sock, rp->ai_addr, rp->ai_addrlen) != -1) { | |
char buf[INET6_ADDRSTRLEN]; | |
struct sockaddr_in *addr_in = (struct sockaddr_in *) rp->ai_addr; | |
inet_ntop(rp->ai_family, &addr_in->sin_addr.s_addr, buf, | |
rp->ai_addrlen); | |
break; | |
} | |
} | |
if (rp == NULL) { | |
throw std::runtime_error("no avaiable address for " + host); | |
} | |
freeaddrinfo(result); | |
return sock; | |
} | |
#include <msgpack.hpp> | |
#include <sys/time.h> | |
void send_msg(int sock) { | |
struct timeval tv; | |
msgpack::sbuffer buf; | |
msgpack::packer <msgpack::sbuffer> pk (&buf); | |
std::string tag("test.tag"); | |
std::string k1("a"), k2("b"); | |
gettimeofday(&tv, NULL); | |
pk.pack_array(3); // [_, _, _] | |
pk.pack(tag); // ["test.tag", _, _] | |
pk.pack(tv.tv_sec); // ["test.tag", 123400xxx, _] | |
pk.pack_map(2); // ["test.tag", 123400xxx, {}] | |
pk.pack(k1); pk.pack(1); // ["test.tag", 123400xxx, {"a": 1}] | |
pk.pack(k2); pk.pack(2); // ["test.tag", 123400xxx, {"a": 1, "b": 2}] | |
write(sock, buf.data(), buf.size()); | |
} | |
int main() { | |
int sock = connect_tcp("localhost", "24224"); | |
send_msg(sock); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment