Skip to content

Instantly share code, notes, and snippets.

@m-mizutani
Created October 27, 2014 06:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m-mizutani/1b0a153120f611aec26e to your computer and use it in GitHub Desktop.
Save m-mizutani/1b0a153120f611aec26e to your computer and use it in GitHub Desktop.
#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(2); // [_, _]
pk.pack(tag); // ["test.tag", _]
pk.pack_array(1); // ["test.tag", [_]]
pk.pack_array(2); // ["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