1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
|
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/time.h> #include <netinet/in.h> #include <unistd.h> #include <ctype.h> int main(int argc, char* argv[]){ int ret; int server_socket; int conn_socket; char RecvBuffer[1024]; char SendBuffer[1024]; struct sockaddr_in server_address; struct sockaddr_in conn_address; fd_set readfds, readcpyfds; memset(RecvBuffer, 0x00, sizeof(RecvBuffer)); memset(SendBuffer, 0x00, sizeof(SendBuffer)); memset(&server_address, 0x00, sizeof(server_address)); memset(&conn_address, 0x00, sizeof(conn_address)); server_socket = socket(AF_INET, SOCK_STREAM, 0); server_address.sin_family = AF_INET; server_address.sin_addr.s_addr = htonl(INADDR_ANY); server_address.sin_port = htons(8888); bind(server_socket, (struct sockaddr*)&server_address, sizeof(server_address)); listen(server_socket, 10); FD_ZERO(&readfds); FD_SET(server_socket, &readfds); while(1){ readcpyfds = readfds;
ret = select(FD_SETSIZE, &readcpyfds, (fd_set*)0, (fd_set*)0, (struct timeval*)0); if(ret < 1) { fprintf(stderr, "select error!\n"); exit(EXIT_FAILURE); } int fd; for(fd = 0; fd < FD_SETSIZE; fd++) { if(FD_ISSET(fd, &readcpyfds)) { if(fd == server_socket) { int size = sizeof(conn_address); conn_socket = accept(server_socket, (struct sockaddr*)&conn_address, &size); FD_SET(conn_socket, &readcpyfds); printf("We have recved a connection!\n"); } else { ret = recv(fd, RecvBuffer, sizeof(RecvBuffer), 0); if(ret < 0){ fprintf(stderr, "recv error!, The error is %s, errno is %d\n", strerror(errno), errno); exit(EXIT_FAILURE); } else if(ret == 0) { printf("recv() time over!\n"); exit(EXIT_FAILURE); } printf("The data we recve is %s\n", RecvBuffer); char* ptr; for(ptr = RecvBuffer; *ptr; ptr++) { *ptr = toupper(*ptr); } strcpy(SendBuffer, RecvBuffer); send(fd, SendBuffer, strlen(SendBuffer), 0); FD_CLR(fd, &readfds); memset(RecvBuffer, 0x00, sizeof(RecvBuffer)); memset(SendBuffer, 0x00, sizeof(SendBuffer)); close(fd); } } } } }
|