C++ 入门

Linux 下的VSCode C++配置:  https://www.cnblogs.com/zhumengke/articles/11629820.html

hello world

#include <iostream>
using namespace std;
int main()
{
    cout << "Hello, world!" << endl;
    return 0;
}

简单服务器

/**
 * a server
 *
 * linux 使用指南
 * g++ -std=c++11 -g -o server main.cpp server.cpp
 * ./server
 */


//server.h

#ifndef __SERVER_H__
#define __SERVER_H__

namespace ztf{
    class Server{
    public:
        Server();
        ~Server();
    public:
        void run();
    };
} //namespace ztf
#endif

//server.cpp
#include <iostream>
#include <unistd.h>
#include "server.h"

namespace ztf{
    Server::Server(){
        std::cout << "Server construct..." << std::endl;
    }
    Server::~Server(){
        std::cout << "Server destruct..." << std::endl;
    }

    void Server::run(){
        while(true){
            std::cout << "the server is running..." << std::endl;
            ::usleep(1000000);
        }
    }
}

//main.cpp
#include <iostream>
#include "server.h"

int main(int argc,char* argv[]){
    ztf::Server* server = new ztf::Server();
    if(server){
        server->run();
    }
    return 0;
}
View Code

 linux 信号处理

// signal
#include <iostream>
#include <unistd.h>
#include <signal.h>

void sighandle(int sig)
{
    std::cout << "sighup received :" << sig << std::endl;
}
int main(int argc,char **argv)
{
       signal(SIGHUP, sighandle);
       signal(SIGINT, sighandle);
       signal(SIGQUIT, sighandle);
       // pause()  causes the calling process (or thread) to sleep until a signal is delivered 
       // that either terminates the process or causes  the  invocation of a signal-catching function.
       pause();  
       return 0;
}


//sigaction
#include <iostream>
#include <unistd.h>
#include <signal.h>

void sighandler(int sig){
  std::cout << "received signal: " << sig << std::endl;
}

int main(int argc, char *argv[])
{
  struct sigaction act, oact;

  act.sa_handler = sighandler;
  sigfillset(&act.sa_mask);
  act.sa_flags = 0;

  sigaction(SIGINT, &act, &oact);
  pause();

  return 0;
}
View Code

UDP Server and UDP Client

// UDP server

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>
#include <iostream>

#define SERVER_PORT 8000

int main(int argc, char *argv[])
{

    char buff_recv[512] = {0};
    char buff_send[512] = "I am a server!";
    int recv_num;
    int send_num;
    int sock_fd;
    int len;

    printf("Welcome! This is a UDP server.\n");

    struct sockaddr_in serverAddr;
    struct sockaddr_in clientAddr;
    memset(&serverAddr, 0, sizeof(struct sockaddr_in)); //每个字节都用0填充
    serverAddr.sin_family = AF_INET;                    //使用IPV4地址
    serverAddr.sin_port = htons(SERVER_PORT);           //端口
    /* INADDR_ANY表示不管是哪个网卡接收到数据,只要目的端口是SERV_PORT,就会被该应用程序接收到 */
    serverAddr.sin_addr.s_addr = htonl(INADDR_ANY); //自动获取IP地址

    len = sizeof(serverAddr);

    sock_fd = socket(AF_INET, SOCK_DGRAM, 0); //sock_fd --- socket文件描述符 创建udp套接字
    if (sock_fd < 0)
    {
        printf("socket error.\n");
        exit(1);
    }

    int ret = bind(sock_fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)); // 绑定socket
    if (ret < 0)
    {
        perror("bind error:");
        exit(1);
    }

    while (true)
    {
        recv_num = recvfrom(sock_fd, buff_recv, sizeof(buff_recv), 0, (struct sockaddr *)&clientAddr, (socklen_t *)&len);

        if (recv_num < 0)
        {

            printf("recv error.\n");
            break;
        }
        else
        {
            buff_recv[recv_num] = 0;
            printf("recv data from client:%s %u says: %s\n", inet_ntoa(clientAddr.sin_addr), ntohs(clientAddr.sin_port), buff_recv);

            send_num = sendto(sock_fd, buff_send, recv_num, 0, (struct sockaddr *)&clientAddr, sizeof(clientAddr));
            if (send_num < 0)
            {

                printf("sendto error.\n");
                break;
            }
        }
    }
    return 0;
}



// UDP Client

#include <sys/types.h>
#include <sys/socket.h>
#include <pthread.h>
#include <netinet/in.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <arpa/inet.h>

#define SERVER_PORT   8000 
#define SERVER_IP   "127.0.0.1" 

int main(int argc, char **argv)
{
    struct sockaddr_in addr;
    int sock;

    addr.sin_family = AF_INET;
    addr.sin_port = htons(SERVER_PORT);
    addr.sin_addr.s_addr = inet_addr(SERVER_IP);

    char buff_send[512] = "I am a client!";
    char buff_recv[512] = {0};
    int len = sizeof(addr);

    int n = 0;

    printf("This is a UDP client\n");

    if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) < 0)
    {
        printf("socket error.\n");
        exit(1);
    }

    if (addr.sin_addr.s_addr == INADDR_NONE)
    {
        printf("Incorrect ip address!");
        close(sock);
        exit(1);
    }

    n = sendto(sock, buff_send, strlen(buff_send), 0, (struct sockaddr *)&addr, sizeof(addr));
    if (n < 0)
    {
        printf("sendto error.\n");
        close(sock);
    }

    n = recvfrom(sock, buff_recv, 512, 0, (struct sockaddr *)&addr, (socklen_t *)&len);
    if (n > 0)
    {
        buff_recv[n] = 0;
        printf("received from sever:");
        puts(buff_recv);
    }
    else if (n == 0)
        printf("server closed.\n");
    else if (n == -1)
        printf("recvfrom error.\n");

    close(sock);

    return 0;
}
View Code

TCP Server and TCP Client

//tcp Server
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8444
#define MESSAGE_SIZE 1024

int main()
{

    int ret = -1;

    int socket_fd = -1;
    int accept_fd = -1;

    int curpos = 0;
    int backlog = 10;
    int flag = 1;

    char recvBuf[MESSAGE_SIZE] = {0};
    char sendBuf[MESSAGE_SIZE] = {0};
    struct sockaddr_in local_addr, remote_addr;

    //create a tcp socket
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1)
    {
        perror("create socket error");
        exit(1);
    }

    //set option of socket
    ret = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    if (ret == -1)
    {
        perror("setsockopt error");
    }

    //set local address
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(PORT);
    local_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(local_addr.sin_zero), 8);

    //bind socket
    ret = bind(socket_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in));
    if (ret == -1)
    {
        perror("bind error");
        exit(1);
    }

    ret = listen(socket_fd, backlog);
    if (ret == -1)
    {
        perror("listen error");
        exit(1);
    }

    //loop
    for (;;)
    {
        int addr_len = sizeof(struct sockaddr_in);
        //accept an new connection
        accept_fd = accept(socket_fd, (struct sockaddr *)&remote_addr, (socklen_t *)&addr_len);
        for (;;)
        {
            memset(recvBuf, 0, sizeof(recvBuf));

            //receive network data and print it
            ret = recv(accept_fd, recvBuf, sizeof(recvBuf), 0);
            if (ret == 0)
            {
                break;
            }
            printf("receive message:%s\n", recvBuf);
            send(accept_fd, recvBuf, sizeof(recvBuf), 0);
        }
        printf("close client connection...\n");
        close(accept_fd);
    }

    printf("quit server...\n");
    close(socket_fd);

    return 0;
}




// tcp client
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>

#define SERVER_IP "127.0.0.1"
#define SERVER_PORT 8444
#define MESSAGE_LENGTH 1024

int main()
{

    int ret = -1;
    int socket_fd;

    //server addr
    struct sockaddr_in serverAddr;

    char sendbuf[MESSAGE_LENGTH];
    char recvbuf[MESSAGE_LENGTH];

    int data_len;

    if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) < 0)
    {
        perror("socket");
        return 1;
    }

    serverAddr.sin_family = AF_INET;
    serverAddr.sin_port = htons(SERVER_PORT);
    serverAddr.sin_addr.s_addr = inet_addr(SERVER_IP);//inet_addr()函数,将点分十进制IP转换成网络字节序IP

    if (connect(socket_fd, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) < 0)
    {
        perror("connect");
        return 1;
    }

    printf("success to connect server...\n");

    while (1)
    {
        memset(sendbuf, 0, MESSAGE_LENGTH);

        printf("<<<<send message:");

        std::cin >> sendbuf;

        ret = send(socket_fd, sendbuf, strlen(sendbuf), 0);
        if (ret <= 0)
        {
            printf("the connection is disconnection!\n");
            break;
        }

        if (strcmp(sendbuf, "quit") == 0)
        {
            break;
        }

        printf(">>> echo message:");

        recvbuf[0] = '\0';
        data_len = recv(socket_fd, recvbuf, MESSAGE_LENGTH, 0);

        recvbuf[data_len] = '\0';

        printf("%s\n", recvbuf);
    }

    close(socket_fd);

    return 0;
}
View Code

 wait and waitpid

#include <stdio.h>
#include <iostream>
#include <unistd.h>
#include <sys/wait.h>

/**
 * fork:
 * On  success,  the PID of the child process is returned in the parent, and 0 is returned in the child. 
 * On failure, -1 is returned in the parent, no child process is created,
 */
int main(int argc, char *argv[])
{

    pid_t pid = -1;

    for (int i = 0; i < 4; i++)
    {
        std::cout << i << std::endl;
        sleep(2);
        if (pid != 0)
        {
            pid = fork();
        }
    }

    if (pid == 0) //子进程
    {
        sleep(2);
    }
    else //主进程
    {
        /**
         * waitpid:
         * pid=-1时,等待任何一个子进程退出,没有任何限制,此时waitpid和wait的作用一模一样。 
         * status用来保存被收集进程退出时的一些状态, NULL不需要收集进程退出的状态
         * options提供了一些额外的选项来控制waitpid
         */ 
        while ((pid = waitpid(-1, NULL, 0)) != -1)
        {
            printf("the pid=%d is dead!\n", pid);
        }
    }
}
View Code

 多进程 + fork

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8111
#define MESSAGE_SIZE 1024

int main()
{

    int ret = -1;

    int pid;
    int socket_fd = -1;
    int accept_fd = -1;

    int curpos = 0;
    int backlog = 10;
    int flag = 1;

    struct sockaddr_in local_addr, remote_addr;

    //create a tcp socket
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1)
    {
        perror("create socket error");
        exit(1);
    }

    //set option of socket
    ret = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &flag, sizeof(flag));
    if (ret == -1)
    {
        perror("setsockopt error");
    }

    //set local address
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(PORT);
    local_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(local_addr.sin_zero), 8);

    //bind socket
    ret = bind(socket_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in));
    if (ret == -1)
    {
        perror("bind error");
        exit(1);
    }

    ret = listen(socket_fd, backlog);
    if (ret == -1)
    {
        perror("listen error");
        exit(1);
    }

    for (;;)
    {

        int addr_len = sizeof(struct sockaddr_in);

        //accept an new connection, block......
        accept_fd = accept(socket_fd, (struct sockaddr *)&remote_addr, (socklen_t *)&addr_len);

        //create a sub process
        pid = fork();

        //子进程
        if (pid == 0)
        {

            char in_buf[MESSAGE_SIZE] = {0};

            for (;;)
            {

                memset(in_buf, 0, MESSAGE_SIZE);

                ret = recv(accept_fd, &in_buf, MESSAGE_SIZE, 0);
                if (ret == 0)
                {
                    break;
                }

                printf("receive message:%s\n", in_buf);
                send(accept_fd, (void *)in_buf, MESSAGE_SIZE, 0);
            }

            printf("close client connection...\n");
            close(accept_fd);
        }

        //parent process
    }

    if (pid != 0)  //主进程
    {
        printf("quit server...\n");
        close(socket_fd);
    }

    return 0;
}
View Code

select

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8888
#define FD_SIZE 1024
#define MESSAGE_SIZE 1024

int main()
{

    int ret = -1;

    int pid;
    int accept_fd = -1;
    int socket_fd = -1;
    int accept_fds[FD_SIZE] = {-1,};

    int curpos = -1;
    int maxpos = 0;
    int backlog = 10;
    int flags = 1; //open REUSEADDR option

    int max_fd = -1;
    fd_set fd_sets;
    int events = 0;

    struct sockaddr_in local_addr, remote_addr;

    //create a tcp socket
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1)
    {
        perror("create socket error");
        exit(1);
    }

    //set option of socket
    ret = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &flags, sizeof(flags));
    if (ret == -1)
    {
        perror("setsockopt error");
    }

    //NONBLOCK
    flags = fcntl(socket_fd, F_GETFL, 0);
    fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);

    //set local address
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(PORT);
    local_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(local_addr.sin_zero), 8);

    //bind socket
    ret = bind(socket_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in));
    if (ret == -1)
    {
        perror("bind error");
        exit(1);
    }

    ret = listen(socket_fd, backlog);
    if (ret == -1)
    {
        perror("listen error");
        exit(1);
    }

    max_fd = socket_fd; //每次都重新设置 max_fd
    for (int i = 0; i < FD_SIZE; i++)
    {
        accept_fds[i] = -1;
    }

    for (;;)
    {

        FD_ZERO(&fd_sets);           //清空sets
        FD_SET(socket_fd, &fd_sets); //将socket_fd 添加到sets

        for (int k = 0; k < maxpos; k++)
        {
            if (accept_fds[k] != -1)
            {
                if (accept_fds[k] > max_fd)
                {
                    max_fd = accept_fds[k];
                }
                printf("fd:%d, k:%d, max_fd:%d\n", accept_fds[k], k, max_fd);
                FD_SET(accept_fds[k], &fd_sets); //继续向sets添加fd
            }
        }

        //遍历所有的fd
        events = select(max_fd + 1, &fd_sets, NULL, NULL, NULL);
        if (events < 0)
        {
            perror("select");
            break;
        }
        else if (events == 0)
        {
            printf("select time out ......");
            continue;
        }
        else if (events)
        {

            printf("events:%d\n", events);

            if (FD_ISSET(socket_fd, &fd_sets))
            { // 如果来的是新连接
                printf("listen event :1\n");

                int a = 0;
                for (; a < FD_SIZE; a++)
                {
                    if (accept_fds[a] == -1)
                    {
                        curpos = a;
                        break;
                    }
                }

                if (a == FD_SIZE)
                {
                    printf("the connection is full!\n");
                    continue;
                }

                int addr_len = sizeof(struct sockaddr_in);
                accept_fd = accept(socket_fd, (struct sockaddr *)&remote_addr, (socklen_t *)&addr_len); //创建一个新连接的fd

                int flags = fcntl(accept_fd, F_GETFL, 0);      //取出新连接的 fd 的相关选项
                fcntl(accept_fd, F_SETFL, flags | O_NONBLOCK); //设置为非阻塞

                accept_fds[curpos] = accept_fd;

                if (curpos + 1 > maxpos)
                {
                    maxpos = curpos + 1;
                }

                if (accept_fd > max_fd)
                {
                    max_fd = accept_fd;
                }

                printf("new connection fd:%d, curpos = %d \n", accept_fd, curpos);
            }

            for (int j = 0; j < maxpos; j++)
            {
                if ((accept_fds[j] != -1) && FD_ISSET(accept_fds[j], &fd_sets))
                { //有事件时
                    printf("accept event :%d, accept_fd: %d\n", j, accept_fds[j]);
                    char in_buf[MESSAGE_SIZE];
                    memset(in_buf, 0, MESSAGE_SIZE);
                    int ret = recv(accept_fds[j], &in_buf, MESSAGE_SIZE, 0);
                    if (ret == 0)
                    {
                        close(accept_fds[j]);
                        accept_fds[j] = -1;
                    }

                    printf("receive message:%s\n", in_buf);
                    send(accept_fds[j], (void *)in_buf, MESSAGE_SIZE, 0);
                }
            }
        }
    }

    printf("quit server...\n");
    close(socket_fd);

    return 0;
}
View Code

epoll

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8888

#define FD_SIZE 20
#define MAX_EVENTS 20
#define TIME_OUT 500

#define MESSAGE_SIZE 1024

int main()
{

    int ret = -1;

    int socket_fd = -1;
    int accept_fd = -1;

    int flags = 1;
    int backlog = 10;

    struct sockaddr_in local_addr, remote_addr;

    struct epoll_event ev, events[FD_SIZE];
    int epoll_fd = -1;
    int event_number = 0;

    //creat a tcp socket
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1)
    {
        perror("create socket error");
        exit(1);
    }

    //set REUSERADDR
    ret = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&flags, sizeof(flags));
    if (ret == -1)
    {
        perror("setsockopt error");
    }

    //set NONBLOCK
    flags = fcntl(socket_fd, F_GETFL, 0);
    fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);

    //set address
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(PORT);
    local_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(local_addr.sin_zero), 8);

    //bind addr
    ret = bind(socket_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in));
    if (ret == -1)
    {
        perror("bind error");
        exit(1);
    }

    if (listen(socket_fd, backlog) == -1)
    {
        perror("listen error");
        exit(1);
    }

    //create epoll
    epoll_fd = epoll_create(256); //the size argument is ignored
    ev.data.fd = socket_fd;
    ev.events = EPOLLIN;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd, &ev); //将socket_fd 添加到epoll中
    for (;;)
    {
        //events 表示一共有多少事件被侦听
        //MAX_EVENTS 表示在events个事件中,本次调用最多能返回多少个被解发的事件
        //TIME_OUT 表示本次调用最多等多长时间
        //event_number 表示本次调用真正有多少事件被解发
        event_number = epoll_wait(epoll_fd, events, MAX_EVENTS, TIME_OUT);
        for (int i = 0; i < event_number; i++)
        {

            if (events[i].data.fd == socket_fd)
            { // 如果是侦听端口的事件

                printf("listen event... \n");

                int addr_len = sizeof(struct sockaddr_in);
                accept_fd = accept(socket_fd, (struct sockaddr *)&remote_addr, (socklen_t *)&addr_len);

                //将新创建的socket设置为 NONBLOCK 模式
                flags = fcntl(accept_fd, F_GETFL, 0);
                fcntl(accept_fd, F_SETFL, flags | O_NONBLOCK);

                ev.data.fd = accept_fd;
                ev.events = EPOLLIN | EPOLLET;
                epoll_ctl(epoll_fd, EPOLL_CTL_ADD, accept_fd, &ev);

                printf("new accept fd:%d\n", accept_fd);
            }
            else if (events[i].events & EPOLLIN)
            {

                //printf("accept event :%d\n",i);

                char in_buf[MESSAGE_SIZE];
                memset(in_buf, 0, MESSAGE_SIZE);

                //receive data
                ret = recv(events[i].data.fd, &in_buf, MESSAGE_SIZE, 0);
                if (ret == MESSAGE_SIZE)
                {
                    printf("maybe have data....");
                }

                if (ret <= 0)
                {

                    switch (errno)
                    {
                    case EAGAIN: //说明暂时已经没有数据了,要等通知
                        break;
                    case EINTR: //被终断了,再来一次
                        printf("recv EINTR... \n");
                        ret = recv(events[i].data.fd, &in_buf, MESSAGE_SIZE, 0);
                        break;
                    default:
                        printf("the client is closed, fd:%d\n", events[i].data.fd);
                        epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, &ev);
                        close(events[i].data.fd);
                        ;
                    }
                }

                printf(">>>receive message:%s\n", in_buf);
                send(events[i].data.fd, &in_buf, ret, 0);
            }
        }
    }
    return 0;
}
View Code

reinterpret_const

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <errno.h>

#include <sys/epoll.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>

#define PORT 8888

#define FD_SIZE 20
#define MAX_EVENTS 20
#define TIME_OUT 500

#define MESSAGE_SIZE 1024

int main()
{

    int ret = -1;

    int socket_fd = -1;
    int accept_fd = -1;

    int flags = 1;
    int backlog = 10;

    struct sockaddr_in local_addr, remote_addr;

    struct epoll_event ev, events[FD_SIZE];
    int epoll_fd = -1;
    int event_number = 0;

    //creat a tcp socket
    socket_fd = socket(AF_INET, SOCK_STREAM, 0);
    if (socket_fd == -1)
    {
        perror("create socket error");
        exit(1);
    }

    //set REUSERADDR
    ret = setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, (char *)&flags, sizeof(flags));
    if (ret == -1)
    {
        perror("setsockopt error");
    }

    //set NONBLOCK
    flags = fcntl(socket_fd, F_GETFL, 0);
    fcntl(socket_fd, F_SETFL, flags | O_NONBLOCK);

    //set address
    local_addr.sin_family = AF_INET;
    local_addr.sin_port = htons(PORT);
    local_addr.sin_addr.s_addr = INADDR_ANY;
    bzero(&(local_addr.sin_zero), 8);

    //bind addr
    ret = bind(socket_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in));
    if (ret == -1)
    {
        perror("bind error");
        exit(1);
    }

    if (listen(socket_fd, backlog) == -1)
    {
        perror("listen error");
        exit(1);
    }

    //create epoll
    epoll_fd = epoll_create(256); //the size argument is ignored
    ev.data.fd = socket_fd;
    ev.events = EPOLLIN;
    epoll_ctl(epoll_fd, EPOLL_CTL_ADD, socket_fd, &ev); //将socket_fd 添加到epoll中
    for (;;)
    {
        //events 表示一共有多少事件被侦听
        //MAX_EVENTS 表示在events个事件中,本次调用最多能返回多少个被解发的事件
        //TIME_OUT 表示本次调用最多等多长时间
        //event_number 表示本次调用真正有多少事件被解发
        event_number = epoll_wait(epoll_fd, events, MAX_EVENTS, TIME_OUT);
        for (int i = 0; i < event_number; i++)
        {

            if (events[i].data.fd == socket_fd)
            { // 如果是侦听端口的事件

                printf("listen event... \n");

                int addr_len = sizeof(struct sockaddr_in);
                accept_fd = accept(socket_fd, (struct sockaddr *)&remote_addr, (socklen_t *)&addr_len);

                //将新创建的socket设置为 NONBLOCK 模式
                flags = fcntl(accept_fd, F_GETFL, 0);
                fcntl(accept_fd, F_SETFL, flags | O_NONBLOCK);

                ev.data.fd = accept_fd;
                ev.events = EPOLLIN | EPOLLET;
                epoll_ctl(epoll_fd, EPOLL_CTL_ADD, accept_fd, &ev);

                printf("new accept fd:%d\n", accept_fd);
            }
            else if (events[i].events & EPOLLIN)
            {

                //printf("accept event :%d\n",i);

                char in_buf[MESSAGE_SIZE];
                memset(in_buf, 0, MESSAGE_SIZE);

                //receive data
                ret = recv(events[i].data.fd, &in_buf, MESSAGE_SIZE, 0);
                if (ret == MESSAGE_SIZE)
                {
                    printf("maybe have data....");
                }

                if (ret <= 0)
                {

                    switch (errno)
                    {
                    case EAGAIN: //说明暂时已经没有数据了,要等通知
                        break;
                    case EINTR: //被终断了,再来一次
                        printf("recv EINTR... \n");
                        ret = recv(events[i].data.fd, &in_buf, MESSAGE_SIZE, 0);
                        break;
                    default:
                        printf("the client is closed, fd:%d\n", events[i].data.fd);
                        epoll_ctl(epoll_fd, EPOLL_CTL_DEL, events[i].data.fd, &ev);
                        close(events[i].data.fd);
                        ;
                    }
                }

                printf(">>>receive message:%s\n", in_buf);
                send(events[i].data.fd, &in_buf, ret, 0);
            }
        }
    }
    return 0;
}
View Code

static_cast

#include <iostream>

class Base
{
public:
    int a;
    int b;
};

class Derived : public Base
{

public:
    int c;
    int d;
};

int main(int argc, char *argv[])
{
    Base *b = new Base();
    Derived *d = new Derived();

    Base *p = static_cast<Base *>(d);
    p->a = 1;
    p->b = 2;

    std::cout << "Base: " << p->a << ", "
              << p->b << std::endl;

    Derived *dp = static_cast<Derived *>(b);
    dp->a = 4;
    dp->b = 5;
    dp->c = 6;
    dp->d = 666;

    std::cout << "Derived: " << dp->a << ", "
              << dp->b << ", "
              << dp->c << ", "
              << dp->d << std::endl;

    return 0;
}
View Code

dynamic_cast

#include <iostream>

class Base {
    public:
        Base(int a, int b){
            this->a = a; 
            this->b = b;
        }
    public:
        virtual void print(){
            std::cout << "member: a=" << a << ", b="
                                      << b << std::endl;
        }
    public:
        int a;
        int b;
};

class Derived1: public Base {
    public:
        Derived1(int a, int b, int o):Base(a, b){
            c = o; 
        }
    public:
        virtual void print(){
            std::cout << "member: a=" << a << ", b="
                                      << b << ", c="
                                      << c << std::endl;
        }
    public:
        int c;
};

class Derived2: public Base {
    public:
        Derived2(int a, int b, int o):Base(a, b){
           d = o; 
        }
    public:
        virtual void print() {
            std::cout << "member: a=" << a << ", b="
                                      << b << ", d="
                                      << d << std::endl;
        }
    public:
        int d;
};

int main(int argc, char* argv[])
{
    Base *b = new Base(1, 2);

    b = dynamic_cast<Base*>(new Derived1(3, 4, 5));
    b->print();

    b = static_cast<Base*>(new Derived2(6, 7, 8));
    b->print();

}
View Code

const_cast

#include <iostream>

class Base {
    public:
        Base(int a, int b){
            this->a = a;
            this->b = b; 
        }

    public:
        int a;
        int b;
};


int main(int argc, char* argv[])
{

    const Base *b = new Base(1, 2);

    std::cout<< "Base: a=" << b->a << ", b="
                           << b->b << std::endl;
    //b->a = 4; 报错
    //b->b = 5; 报错

    Base *pb = const_cast<Base*>(b);

    pb->a = 3;
    pb->b = 4;


    std::cout<< "Base: a=" << pb->a << ", b="
                           << pb->b << std::endl;

    return 0;

}
View Code

const_point

#include <stdio.h>

int main(int argc, char* argv[])
{
    int p = 3;
    int a = 4;
    const int pp = 4;
    const int *point = &pp;

    int const *p2 = &pp;

    int* const p3 = &p;

    const int* const p4 = &p;
    int const * const p5 = &p;


    printf("p = %d \n", p);
    //////////////////////////

    printf("pp = %d \n", pp);
    //pp  = 5; //报错
    //////////////////////////

    printf("*point = %d \n", *point);
    //*point = 7; //报错
    point = &p;
    printf("*point = %d \n", *point);

    //////////////////////////
    
    printf("*p2 = %d \n", *p2);
    //*p2 = 8; //报错
    p2 = &p;
    printf("*p2 = %d \n", *p2);

    //////////////////////////
    printf("*p3 = %d \n", *p3);
    *p3 = 9;
    printf("*p3 = %d \n", *p3);
    //p3 = &a; //报错
    //////////////////////////

    printf("*p4 = %d \n", *p4);
    //*p4 = 9; //报错
    //p4 = &a; //报错
    //
    //////////////////////////

    printf("*p5 = %d \n", *p5);
    //*p5 = 9; //报错
    //p5 = &a; //报错

}
View Code

 

 

 

vs2017 添加lib和头文件

如果我们借鉴别人写好的代码,放进vs2010编译器时常常出现这样的报错,无法打开源文件 “stdafx.h”: 

这是因为在低版本的编译器中,需要添加这部分,比如vc6.0到vs2008,而在vs2010以上版本的编译器中如果出现了这种报错,就查看一下属性->c/c++->预编译头->预编译头文件,其中是否包含了”stdafx.h”文件,如果有注释掉上述代码就好,不会对程序造成影响。 

VS2017添加lib库及其头文件

A、添加工程的头文件目录:工程---属性---配置属性---c/c++---常规---附加包含目录:加上头文件存放目录。
B、添加文件引用的lib静态库路径:工程---属性---配置属性---链接器---常规---附加库目录:加上lib文件存放目录。
C 然后添加工程引用的lib文件名:工程---属性---配置属性---链接器---输入---附加依赖项:加上lib文件名

创建类对象

栈中创建: Human human;     // 会自动调用析构函数

堆中创建:Human* p  = new Human();   // 不会自动调用析构函数,需要显示的调用delete方法,否则会造成内存泄漏

posted @ 2019-10-07 14:12  逐梦客!  阅读(205)  评论(0编辑  收藏  举报