3C科技 娛樂遊戲 美食旅遊 時尚美妝 親子育兒 生活休閒 金融理財 健康運動 寰宇綜合

Zi 字媒體

2017-07-25T20:27:27+00:00
加入好友
這組code是從http://www.programminglogic.com/sockets-programmin...擷錄 先收下改天必有用處 Server Code /******************* SERVER CODE *****************/ #include #include #include #include #include int main(){   int welcomeSocket, newSocket, portNum, clientLen, nBytes;   char buffer[1024];   struct sockaddr_in serverAddr;   struct sockaddr_storage serverStorage;   socklen_t addr_size;   int i;   welcomeSocket = socket(PF_INET, SOCK_STREAM, 0);   portNum = 7891;      serverAddr.sin_family = AF_INET;   serverAddr.sin_port = htons(portNum);   serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");   memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);     bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr));   if(listen(welcomeSocket,5)==0)     printf("Listening\n");   else     printf("Error\n");   addr_size = sizeof serverStorage;   /*loop to keep accepting new connections*/   while(1){     newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size);     /*fork a child process to handle the new connection*/     if(!fork()){       nBytes = 1;       /*loop while connection is live*/       while(nBytes!=0){         nBytes = recv(newSocket,buffer,1024,0);            for (i=0;i           buffer[i] = toupper(buffer[i]);         }         send(newSocket,buffer,nBytes,0);       }       close(newSocket);       exit(0);     }     /*if parent, close the socket and go back to listening new requests*/     else{       close(newSocket);     }   }   return 0; } Client Code /******************* CLIENT CODE *****************/ #include #include #include #include int main(){   int clientSocket, portNum, nBytes;   char buffer[1024];   struct sockaddr_in serverAddr;   socklen_t addr_size;   clientSocket = socket(PF_INET, SOCK_STREAM, 0);   portNum = 7891;   serverAddr.sin_family = AF_INET;   serverAddr.sin_port = htons(portNum);   serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");   memset(serverAddr.sin_zero, '\0', sizeof serverAddr.sin_zero);     addr_size = sizeof serverAddr;   connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size);   while(1){     printf("Type a sentence to send to server:\n");     fgets(buffer,1024,stdin);     printf("You typed: %s",buffer);     nBytes = strlen(buffer) + 1;     send(clientSocket,buffer,nBytes,0);     recv(clientSocket, buffer, 1024, 0);     printf("Received from server: %s\n\n",buffer);      }   return 0; }

本文由charleslin74pixnetnetblog提供 原文連結

寫了 5860316篇文章,獲得 23313次喜歡
精彩推薦