2022-4-11 修改TCP发送缓冲区大小

设置发送缓冲区的大小

#include
#include
#include
#include
#include
#define BUFFER_SIZE 512
//接受缓冲区设置为50,发送缓冲区设置为2000
int main(int argc,char *argv[]){
    //1.创建套接字
    int fd = socket(AF_INET,SOCK_STREAM,0);
    if(fd == -1){
        perror("socket");
        exit(0);
    }
    //设置发送缓冲区的大小。
    int sendbuf = 2000;
    int len = sizeof(sendbuf);
    setsockopt(fd,SOL_SOCKET,SO_SNDBUF,&sendbuf,sizeof(sendbuf));
    getsockopt(fd,SOL_SOCKET,SO_SNDBUF,&sendbuf,(socklen_t*)&len);
    printf("the tcp send buffer size after setting is %d\n",sendbuf);

    //2.连接服务器
    struct sockaddr_in server_addr;
    server_addr.sin_family = AF_INET;
    inet_pton(PF_INET,"192.168.131.137",&server_addr.sin_addr);
    server_addr.sin_port = htons(9999);
    int ret = connect(fd,(struct sockaddr*)&server_addr,sizeof(server_addr));
    if(ret == -1){
        perror("connect");
        exit(0);
    }
    char buffer[BUFFER_SIZE];
    memset(buffer,'a',BUFFER_SIZE);
    send(fd,buffer,BUFFER_SIZE,0);
    close(fd);
    return 0;
}

在这里插入图片描述
设置接收缓冲区的大小

#include
#include
#include
#include
#include
#define BUFFER_SIZE 1024
int main(void){
    int fd = socket(AF_INET,SOCK_STREAM,0);
    if(fd == -1){
        perror("socket");
        exit(0);
    }
    //2.设置接收缓存区的大小为50
    int recvbuf = 50;
    int len = sizeof(recvbuf);
    setsockopt(fd,SOL_SOCKET,SO_RCVBUF,&recvbuf,sizeof(recvbuf));
    getsockopt(fd,SOL_SOCKET,SO_RCVBUF,&recvbuf,(socklen_t*)&len);

    printf("the tcp recevie buffer size after setting is %d\n",recvbuf);

    //2.绑定
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(9999);

    int ret = bind(fd,(struct sockaddr*)&addr,sizeof(addr));
    if(ret == -1){
        perror("bind");
        exit(0);
    }

    //3.监听
    ret = listen(fd,8);
    if(ret == -1){
        perror("listen");
        exit(0);
    }
    //4.接收客户端连接
    struct sockaddr_in client_addr;
    socklen_t addrlen = sizeof(client_addr);
    int cfd = accept(fd,(struct sockaddr*)&client_addr,&addrlen);
    if(cfd == -1){
        perror("accept");
        exit(0);
    }
    //5.输出客户端信息
    char ClientIP[16];
    inet_ntop(AF_INET,&client_addr.sin_addr.s_addr,ClientIP,sizeof(ClientIP));
    unsigned short clientPort = ntohs(client_addr.sin_port);
    printf("client ip is %s, port is %d.\n",ClientIP,clientPort);
    //原来连接的信息就有端口号的,看来自己要将这段代码多敲几遍。

    //6.获取客户端的数据
    char buffer[BUFFER_SIZE];
    memset(buffer,'\0',BUFFER_SIZE);
    while (recv(cfd,buffer,BUFFER_SIZE -1,0) > 0){}
    close(cfd);
    close(fd);
    return 0;
}

2022-4-11 修改TCP发送缓冲区大小_第1张图片

你可能感兴趣的:(网络编程,网络编程)