一、select
使用select函数可以将多个文件描述符集中到一起统一监视,监视事件如下:
- 是否存在待读取数据。
- 是否可传输无阻塞传输数据。
- 是否发生异常。
将关心上述3种事件的文件描述发分别注册到对应参数(readfds,writefds,exceptfds)中去。
int select(int nfds, fd_set FAR * readfds, fd_set FAR * writefds, fd_set FAR * exceptfds, const struct timeval FAR * timeout);
1、linux
服务器端:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h> #define BUF_SIZE 1024
void error_handling(char * messages); int main(int argc, char *argv[])
{
if(argc != )
{
printf("Usage : %s <port>\n", argv[]);
exit();
}
int serverSock, clientSock;
struct sockaddr_in serverAddr, clientAddr;
socklen_t clientAddrSize; struct timeval timeout;
fd_set reads, cpy_reads;
int fd_max, fd_num; char message[BUF_SIZE];
int strLen; serverSock =socket(PF_INET, SOCK_STREAM, );
if(serverSock == -)
error_handling("socket() error"); memset(&serverAddr, , sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddr.sin_port = htons(atoi(argv[])); if(bind(serverSock, (struct sockaddr*) &serverAddr, sizeof(serverAddr)) == -)
error_handling("bind() error");
if(listen(serverSock, ) == -)
error_handling("listen() error"); FD_ZERO(&reads);
FD_SET(serverSock, &reads);
fd_max = serverSock; puts("Server start...");
while(){
cpy_reads = reads;
timeout.tv_sec = ;
timeout.tv_usec = ; if((fd_num = select(fd_max+, &cpy_reads, , , &timeout)) == -){
error_handling("select() error");
break;
}
if(fd_num == ) continue;
for(int i = ; i <= fd_max; i++){
if(FD_ISSET(i, &cpy_reads)){
if(i == serverSock){ // connection request
clientAddrSize = sizeof(clientAddr);
clientSock = accept(serverSock, (struct sockaddr*)&clientAddr, &clientAddrSize);
FD_SET(clientSock, &reads);
if(fd_max < clientSock)
fd_max = clientSock;
printf("connected client: %d\n", clientSock);
}
else{ // read message
strLen = read(i, message, BUF_SIZE);
if(strLen == ){
FD_CLR(i, &reads);
close(i);
printf("close client: %d\n", i);
}
else{
write(i, message, strLen);
printf("echo: %d\n",i);
}
}
}
}
}
close(serverSock);
puts("Server close...");
return ;
} void error_handling(char * messages)
{
puts(messages);
exit();
}
客户端:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h> #define BUF_SIZE 1024
void error_handling(char * messages); int main(int argc, char *argv[])
{
if(argc != )
{
printf("Usage : %s <IP> <port>\n", argv[]);
exit();
}
int sock;
struct sockaddr_in serv_addr;
char message[BUF_SIZE];
int strLen; sock = socket(PF_INET, SOCK_STREAM, );
if(sock == -)
error_handling("socket() error"); memset(&serv_addr, , sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = inet_addr(argv[]);
serv_addr.sin_port = htons(atoi(argv[])); if(connect(sock, (struct sockaddr*) &serv_addr, sizeof(serv_addr)) == -)
error_handling("connect() error");
else
puts("Connected...");
while(){
puts("Input message(Q to quit):");
fgets(message, BUF_SIZE, stdin);
if(!strcmp(message, "q\n") || !strcmp(message, "Q\n"))
break; strLen=strlen(message);
write(sock, message, strlen(message));
int recvLen = ;
while(recvLen < strLen){
int recvCnt = read(sock, &message[recvLen], BUF_SIZE-);
if(recvCnt == -)
error_handling("read() error");
recvLen+=recvCnt;
}
message[recvLen]=;
printf("Message from server: %s\n", message);
}
close(sock);
return ;
} void error_handling(char * messages)
{
puts(messages);
exit();
}
2、windows
服务器端:
#include <stdio.h>
#include <stdlib.h>
#include <WinSock2.h> #define BUF_SIZE 1024
void ErrorHandling(char *message); int main(int argc, char *argv[])
{
if (argc != ) {
printf("Usage : %s <port>\n", argv[]);
exit();
} WSADATA wsa_data;
SOCKET server_sock, client_sock;
SOCKADDR_IN server_addr, client_addr;
TIMEVAL time_out;
fd_set reads, temp_reads; int addr_size;
int str_len, fd_num;
char buf[BUF_SIZE]; if (WSAStartup(MAKEWORD(, ), &wsa_data) != )
ErrorHandling("WSAStartup() error."); server_sock = socket(PF_INET, SOCK_STREAM, );
if (server_sock == INVALID_SOCKET)
ErrorHandling("socket() error."); memset(&server_addr, , sizeof(server_addr));
server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
server_addr.sin_port = htons(atoi(argv[])); if (bind(server_sock, (SOCKADDR*)&server_addr, sizeof(server_addr)) == SOCKET_ERROR)
ErrorHandling("bind() error.");
if (listen(server_sock, ) == SOCKET_ERROR)
ErrorHandling("listen() error.");
printf("Server start...\n");
FD_ZERO(&reads);
FD_SET(server_sock, &reads);
while (true)
{
temp_reads = reads;
time_out.tv_sec = ;
time_out.tv_usec = ;
if ((fd_num = select(, &temp_reads, , , &time_out)) == SOCKET_ERROR)
break;
if (fd_num == )
continue;
for (int i = ; i < reads.fd_count; ++i)
{
if (FD_ISSET(reads.fd_array[i], &temp_reads))
{
if (reads.fd_array[i] == server_sock) // connection request
{
addr_size = sizeof(client_addr);
client_sock = accept(server_sock, (SOCKADDR*)&client_addr, &addr_size);
if (client_sock == INVALID_SOCKET)
ErrorHandling("accept() error.");
FD_SET(client_sock, &reads);
printf("connected client: %d\n", client_sock);
}
else // read message
{
str_len = recv(reads.fd_array[i], buf, BUF_SIZE - , );
if (str_len == )
{
FD_CLR(reads.fd_array[i], &reads);
closesocket(temp_reads.fd_array[i]);
printf("close client: %d\n", temp_reads.fd_array[i]);
}
else
{
send(reads.fd_array[i], buf, str_len, ); // echo
}
}
}
}
}
closesocket(server_sock);
WSACleanup();
printf("Server end...\n");
return ;
} void ErrorHandling(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
}
客户端:
#pragma warning(disable:4996)
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h> #define BUF_SIZE 1024
void ErrorHandling(char *message); int main(int argc, char* argv[]) {
if (argc != ) {
printf("Usage : %s <IP> <port>\n", argv[]);
exit();
} WSADATA wsaData;
SOCKET sock;
SOCKADDR_IN serverAddr;
char message[BUF_SIZE];
int sLen, recvLen; if (WSAStartup(MAKEWORD(, ), &wsaData) != )
ErrorHandling("WSAStartup() error"); sock = socket(PF_INET, SOCK_STREAM, );
if (sock == INVALID_SOCKET)
ErrorHandling("socket() error"); memset(&serverAddr, , sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = inet_addr(argv[]);
serverAddr.sin_port = htons(atoi(argv[])); if (connect(sock, (SOCKADDR*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR)
ErrorHandling("connect() error");
else
printf("Connected.......\n");
while ()
{
fputs("Input message(Q to quit):", stdout);
fgets(message, BUF_SIZE, stdin);
if (!strcmp(message, "q\n") || !strcmp(message, "Q\n"))
break;
sLen = send(sock, message, strlen(message), );
recvLen = ;
while (recvLen < sLen) {
int cnt = recv(sock, message, BUF_SIZE - , );
if (cnt == -)
ErrorHandling("ercv() error");
recvLen += cnt;
}
message[recvLen] = ;
printf("Message from server: %s\n", message);
}
closesocket(sock);
WSACleanup();
return ;
} void ErrorHandling(char *message) {
fputs(message, stderr);
fputc('\n', stderr);
}