博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
网络编程-第一种netcat代码解析
阅读量:3770 次
发布时间:2019-05-22

本文共 2133 字,大约阅读时间需要 7 分钟。

#include "Acceptor.h"#include "InetAddress.h"#include "TcpStream.h"#include 
#include
#include
int write_n(int fd, const void* buf, int length){
int written = 0; while (written < length) {
int nw = ::write(fd, static_cast
(buf) + written, length - written); if (nw > 0) {
written += nw; } else if (nw == 0) {
break; // EOF } else if (errno != EINTR) {
perror("write"); break; } } return written;}void run(TcpStreamPtr stream){
// Caution: a bad example for closing connection std::thread thr([&stream] () {
char buf[8192]; int nr = 0; // 接收stdin(输入缓冲区)数据,发送给服务器 while ( (nr = stream->receiveSome(buf, sizeof(buf))) > 0) {
int nw = write_n(STDOUT_FILENO, buf, nr); if (nw < nr) {
break; } } ::exit(0); // should somehow notify main thread instead }); //接收服务器信息,接收后输出到stdout(输出缓冲区) char buf[8192]; int nr = 0; while ( (nr = ::read(STDIN_FILENO, buf, sizeof(buf))) > 0) {
int nw = stream->sendAll(buf, nr); if (nw < nr) {
break; } } stream->shutdownWrite(); thr.join();}int main(int argc, const char* argv[]){
if (argc < 3) {
printf("Usage:\n %s hostname port\n %s -l port\n", argv[0], argv[0]); return 0; } int port = atoi(argv[2]); // 服务器-l if (strcmp(argv[1], "-l") == 0) {
std::unique_ptr
acceptor(new Acceptor(InetAddress(port))); TcpStreamPtr stream(acceptor->accept()); if (stream) {
acceptor.reset(); // stop listening run(std::move(stream)); } else {
perror("accept"); } } else //客户端 {
InetAddress addr(port); const char* hostname = argv[1]; if (InetAddress::resolve(hostname, &addr)) {
TcpStreamPtr stream(TcpStream::connect(addr)); if (stream) {
run(std::move(stream)); } else {
printf("Unable to connect %s\n", addr.toIpPort().c_str()); perror(""); } } else {
printf("Unable to resolve %s\n", hostname); } }}

转载地址:http://cfhpn.baihongyu.com/

你可能感兴趣的文章
【干货】建议收藏! ! !全网最全的Python.openpyxl操作Excel数据
查看>>
Python如何将CSV文件转化为HTML文件?
查看>>
小白的我当年最得意的登录界面(JavaScript)
查看>>
计组期末复习题(3)
查看>>
计组期末复习题(4)
查看>>
计组期末复习题(5)
查看>>
计组期末开卷资料
查看>>
计组期末复习题获取
查看>>
c++(STL中一些常用操作)
查看>>
php(环境搭建)
查看>>
php(变量)
查看>>
php(单双引号的区别)
查看>>
php(数据类型)
查看>>
php(运算符及流程控制)
查看>>
php(自定义函数与系统自带函数)
查看>>
php(从一个文件中调用另一个文件的变量)
查看>>
php(数组及相关操作)
查看>>
php(about error and time)
查看>>
利用php对数据库进行操作
查看>>
二叉树及其(前中后)序遍历
查看>>