Skip to content

Instantly share code, notes, and snippets.

@kumagi

kumagi/slow_client.cpp

Last active Mar 22, 2017
Embed
What would you like to do?
#include <sys/socket.h>
#include <thread>
#include <iostream>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(12345);
addr.sin_addr.s_addr = inet_addr("127.0.0.1");
int cnt = 0;
for (;;) {
std::this_thread::sleep_for(std::chrono::milliseconds(10));
int cli = ::socket(AF_INET, SOCK_STREAM, 0);
if (::connect(cli, (struct sockaddr *)&addr, sizeof(addr)) == 0) {
perror("connect");
}
std::string buff(std::to_string(cnt) + "th");
int nwrite = ::write(cli, buff.c_str(), buff.size());
if (nwrite == -1) {
perror("write");
} else if (nwrite == buff.size()) {
std::cout << buff << std::endl;
++cnt;
} else {
std::cout << nwrite << " bytes wrote" << std::endl;
}
::close(cli);
}
}
#include <sys/socket.h>
#include <thread>
#include <iostream>
#include <unistd.h>
#include <netinet/in.h>
int main() {
int svr = ::socket(AF_INET, SOCK_STREAM, 0);
sockaddr_in svr_addr;
svr_addr.sin_family = AF_INET;
svr_addr.sin_port = htons(12345);
svr_addr.sin_addr.s_addr = INADDR_ANY;
bind(svr, (struct sockaddr *)&svr_addr, sizeof(svr_addr));
::listen(svr, 2);
for (;;) {
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
sockaddr addr;
socklen_t len;
int sock = ::accept(svr, &addr, &len);
std::cout << sock << " accepted" << std::endl;
char buff[4096];
int nread = ::read(sock, buff, 4096);
std::cout << std::string(buff, nread) << std::endl;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment