服务器代码
这个写法的本质是一个客户端起一个线程,用了高级的C++11和智能指针,本质上可以改为低级的代码
#include <thread>
#include <string.h>
// a thread-per-connection current echo server
int main(int argc, char* argv[])
{
InetAddress listenAddr(3007);
Acceptor acceptor(listenAddr);
printf("Accepting... Ctrl-C to exit\n");
int count = 0;
bool nodelay = argc > 1 && strcmp(argv[1], "-D") == 0;
while (true)
{
TcpStreamPtr tcpStream = acceptor.accept();
printf("accepted no. %d client\n", ++count);
if (nodelay)
tcpStream->setTcpNoDelay(true);
// C++11 doesn't allow capturing unique_ptr in lambda, C++14 allows.
std::thread thr([count] (TcpStreamPtr stream) {
printf("thread for no. %d client started.\n", count);
char buf[4096];
int nr = 0;
while ( (nr = stream->receiveSome(buf, sizeof(buf))) > 0)
{
int nw = stream->sendAll(buf, nr);
if (nw < nr)
{
break;
}
}
printf("thread for no. %d client ended.\n", count);
}, std::move(tcpStream));
thr.detach();
}
}
客户端代码
命令行指定了发送字节数
#include "InetAddress.h"
#include "TcpStream.h"
#include <unistd.h>
int main(int argc, const char* argv[])
{
if (argc < 3)
{
printf("Usage: %s hostname message_length [scp]\n", argv[0]);
return 0;
}
const int len = atoi(argv[2]);
InetAddress addr(3007);
if (!InetAddress::resolve(argv[1], &addr))
{
printf("Unable to resolve %s\n", argv[1]);
return 0;
}
printf("connecting to %s\n", addr.toIpPort().c_str());
TcpStreamPtr stream(TcpStream::connect(addr));
if (!stream)
{
perror("");
printf("Unable to connect %s\n", addr.toIpPort().c_str());
return 0;
}
printf("connected, sending %d bytes\n", len);
std::string message(len, 'S');
int nw = stream->sendAll(message.c_str(), message.size());
printf("sent %d bytes\n", nw);
if (argc > 3)
{
for (char cmd : std::string(argv[3]))
{
if (cmd == 's') // shutdown
{
printf("shutdown write\n");
stream->shutdownWrite();
}
else if (cmd == 'p') // pause
{
printf("sleeping for 10 seconds\n");
::sleep(10);
printf("done\n");
}
else if (cmd == 'c') // close
{
printf("close without reading response\n");
return 0;
}
else
{
printf("unknown command '%c'\n", cmd);
}
}
}
std::vector<char> receive(len);
int nr = stream->receiveAll(receive.data(), receive.size());
printf("received %d bytes\n", nr);
if (nr != nw)
{
printf("!!! Incomplete response !!!\n");
}
}
当发送数据量比较大的时候,这个程序会卡死,一直阻塞下去
所以不能简单使用阻塞IO读取数据