转自:http://www.cnblogs.com/coder2012/archive/2013/03/31/2991785.html
设置套接字函数:
#include<sys/socket.h> int setsockopt(int sockfd, int level, int optname, const void* optval, socklen_t* optlen); //sockfd要设置的目的套接字 //level套接字的控制层次 //optname optval optlen是三个相关的参数,通过不同的搭配可以设置不同的功能
应用:
1.数据收发时限设置
struct timeva timeout; timeout.tv_sec=5; timeout.tv_usec=0; //接受时限 setsockopt(serversocket, SQL_SOCKET,SO_RCVTIMEO, (char*)&timeout,sizeof(timeout)); //发送时限 setsockopt(serversocket, SQL_SOCKET,SO_SNDTIMEO, (char*)&timeout,sizeof(timeout));
2.修改收发缓冲区
//接收缓冲区 int opt=1024*1024; setsockopt(serversocket, SQL_SOCKET, SO_RCVBUF, (const char*)&opt,sizeof(opt)); //发送缓冲区 setsockopt(serversocket, SQL_SOCKET, SO_SNDBUF, (const char*)&opt,sizeof(opt));
3.广播设置
int bBroadcast=1; setsockopt(seversocket, SQL_SOCKET, SO_BROADCAST,(cosnt char*)&bBroadcast,sizeof(bBroadcast));
4.直接数据复制
为了提升系统性能,在发送或接受数据时,可以主动设置数据不经历由缓冲区到套接字缓存区的拷贝。
int opt=0; setsockopt(serversocket, SQL_SOCKET,SO_SNDBUF,(char*)&opt,sizeof(opt)); setsockopt(serversocket, SQL_SOCKET,SO_RCVBUF,(char*)&opt,sizeof(opt));
Select技术:
#include <stdio.h> #include <sys/socket.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <errno.h> #include <netinet/in.h> #include <arpa/inet.h> #include <string.h> #define SERVER_PORT 5555 #define QUEUE_LENGTH 5 #define BUF_SIZE 200 int main(int argc, char **argv) { int server_socket,new_socket; struct sockaddr_in server_addr,client_addr; socklen_t sin_size; int client_socket[QUEUE_LENGTH]; int conn_num; int yes=1; char buf[BUF_SIZE]; int ret; int i; //创建套接字 if((server_socket=socket(AF_INET,SOCK_STREAM,0))<0){ perror("Socket"); return 0; } //设置为可重复使用 if(setsockopt(server_socket,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int))==-1){ perror("setsockopt"); return 0; } //设置服务器地址信息设置 server_addr.sin_family=AF_INET; //TCP server_addr.sin_port=htons(SERVER_PORT); server_addr.sin_addr.s_addr=INADDR_ANY; //本地IP地址 memset(server_addr.sin_zero,'