跳至主要內容
Linux select实现socket单线程多路复用

select版本比阻塞版本的性能起码高了3倍+

# select版本
dhb@dev:~/下载/webbench-1.5$ webbench -c 1000 -t 30 http://127.0.0.1:1500/t
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://127.0.0.1:1500/t
1000 clients, running 30 sec.

Speed=735248 pages/min, 269580 bytes/sec.
Requests: 367610 susceed, 14 failed.

# 阻塞版本
dhb@dev:~/下载/webbench-1.5$ webbench -c 1000 -t 30 http://127.0.0.1:1500/t
Webbench - Simple Web Benchmark 1.5
Copyright (c) Radim Kolar 1997-2004, GPL Open Source Software.

Benchmarking: GET http://127.0.0.1:1500/t
1000 clients, running 30 sec.

Speed=261244 pages/min, 95729 bytes/sec.
Requests: 130540 susceed, 82 failed.


DHB大约 4 分钟网络LinuxSocketIO
Linux socket笔记

linux socket创建tcp连接例子

代码

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


using namespace std;

int main() {
    int client;

    /*
     * socket函数的方法签名
     * int socket (int __family, int __type, int __protocol)
     * __family     定义协议族
     * __type       定义数据传输方式/套接字类型
     * __protocol   定义传输协议
     *
     * 返回值是文件描述符
     *
     * */
    client = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);

    if (client < 0) {
        cout << "=> 连接失败" << endl;
    }

    /*
    * 位于netinet/in.h
    * 将套接字和IP、端口判断
    *
    * */
    struct sockaddr_in server_addr{};
    // 使用IPv4
    server_addr.sin_family = AF_INET;
    // 端口
    server_addr.sin_port = htons(1500);
    // IP地址
    server_addr.sin_addr.s_addr = htons(INADDR_ANY);

    /*
     * struct sockaddr* 位于socket.h
     * bind()签名
     * int bind (int, const struct sockaddr *__my_addr, socklen_t __addrlen);
     * 第一个参数:socket文件描述符
     * 第二个参数:struct sockaddr*
     * 第三个参数:struct sockaddr* 长度
     * */
    if (bind(client, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0) {
        cout << "=> 绑定socket异常" << endl;
        exit(1);
    }


    // 设置监听
    listen(client, SOMAXCONN);

    struct sockaddr_in client_addr{};
    socklen_t client_addr_len = sizeof(client_addr);
    int server;
    while (true) {
        server = accept(client, (struct sockaddr *) &client_addr, &client_addr_len);

        if (server < 0) {
            cout << "=> accept 错误" << endl;
            exit(1);
        }
        // todo 写怎么接收数据
    }
}

DHB大约 1 分钟网络LinuxSocketIO