udp-select的使用

记录简单用例:

server 头文件:

#include 
#include 
#include 
#include 
#include 
#include 

class ServerNet
{
public:
    ServerNet();
    ~ServerNet();
    bool socketInit(int port);
    bool dostart();
    void exit();
private:
    bool isloop;
    struct sockaddr_in local_addr;
    int sock_fd;
};

cpp文件

#include "selectudp.h"
#include 
#include 
#define BUFFERSIZE 2048

ServerNet::ServerNet()
{

}

ServerNet::~ServerNet()
{
}

bool ServerNet::socketInit(int port)
{
    //初始化udp
    sock_fd = -1;
    sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock_fd < 0)
    {
        std::cout << "socket init  err" << std::endl;
        return false;
    }
    do
    {
        // 设置本地端口信息
        memset(&local_addr, 0, sizeof(local_addr));
        local_addr.sin_family = AF_INET;
        local_addr.sin_addr.s_addr = INADDR_ANY;//inet_addr("127.0.0.1");//
        local_addr.sin_port = htons(port);

        // bind端口
        int ret = bind(sock_fd, (struct sockaddr *)&local_addr, sizeof(struct sockaddr_in));
        if (ret != 0)
        {
            std::cout << "socket bind failed" << std::endl;
            break;
        }

        // // 设置超时
        // struct timeval tv;
        // tv.tv_sec = 1;
        // tv.tv_usec = 0;

        // if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, (char *)&tv, sizeof(tv)) != 0)
        // {
        //     std::cout << "socket setovertime failed" << std::endl;
        //     break;
        // }
        //成功
        return true;

    } while (0);
    //失败
    close(sock_fd);
    return false;
}

//数据处理接收
bool ServerNet::dostart()
{
    char buf[BUFFERSIZE]={0};
    struct sockaddr_in remote_addr;
    socklen_t remote_len = sizeof(remote_addr);
    isloop = true;

    fd_set read_fds;
    struct timeval tv;

    while(isloop)
    {
        //使用select io复用
        FD_ZERO(&read_fds);
        FD_SET(sock_fd, &read_fds);
       
        //每次都会重置
        tv.tv_sec = 1;
        tv.tv_usec = 0;

        int num = select(sock_fd+1, &read_fds, NULL, NULL, &tv);
        if (num <= 0)
        {
            std::cout<<"select no fd"<#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

int main() {
    int port = 15006;
    int sockfd;
    struct sockaddr_in addr;
    char send_buf[] = "i am send.";
    int send_num = 0;

    sockfd = socket(AF_INET, SOCK_DGRAM, 0);

    memset(&addr, 0, sizeof(addr));
    addr.sin_family = AF_INET;
    addr.sin_port = htons(port);
    addr.sin_addr.s_addr = inet_addr("127.0.0.1");


    while (1) {
        sleep(3);
        send_num = sendto(sockfd, (char*)send_buf, (size_t) sizeof(send_buf), 0, (struct sockaddr *)&addr, (socklen_t)sizeof(addr));
        cout<<"send bytes: "<

你可能感兴趣的:(linux,udp,网络协议,网络)