设置发送缓冲区的大小
#include<stdio.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#define BUFFER_SIZE 512
int main(int argc,char *argv[]){
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);
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<stdio.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
#define BUFFER_SIZE 1024
int main(void){
int fd = socket(AF_INET,SOCK_STREAM,0);
if(fd == -1){
perror("socket");
exit(0);
}
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);
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);
}
ret = listen(fd,8);
if(ret == -1){
perror("listen");
exit(0);
}
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);
}
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);
char buffer[BUFFER_SIZE];
memset(buffer,'\0',BUFFER_SIZE);
while (recv(cfd,buffer,BUFFER_SIZE -1,0) > 0){}
close(cfd);
close(fd);
return 0;
}
|