日期:2014-05-16 浏览次数:20673 次
本次的主题是基本网络编程:socket,涉及到的概念比较多,就不详细展开了。从编程角度简单的说,为了在客户端和服务器之间建立一个连接,服务器端需要依次调用这些函数:
#include <arpa/inet.h> #include <stdio.h> #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <errno.h> #include <string.h> #include <unistd.h> int main(int argc, char *argv[]) { int numPort, lenMsg, i; int sockServ, sockClient; struct sockaddr_in adrServ, adrClient; char message[256]; char * overMsg = "over"; int adrSize = sizeof(adrClient); int yes = 1; if(argc < 2) { printf("syntaxe : %s numPort\n", argv[0]); return -1; } //set local addr and port numPort = atoi(argv[1]); adrServ.sin_addr.s_addr = INADDR_ANY; adrServ.sin_family = AF_INET; adrServ.sin_port = htons(numPort); bzero(&(adrServ.sin_zero), 8) ; //Get a socket if((sockServ = socket(PF_INET, SOCK_STREAM, 0)) == -1) { perror("sockServet"); return -1; } //We can set some param here.// paramètrage de la socket pour réutiliser le N° ce port sans délai if(setsockopt(sockServ, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) { perror("setsockopt"); return -1; } // bind if(bind(sockServ, (struct sockaddr *)(&adrServ), sizeof(adrServ)) == -1) { perror("bind"); return -1; } // place la socket en écoute if(listen(sockServ, 1) == -1) { perror("listen"); return -1; } // wait for a connection from a client if((sockClient = accept(sockServ, (struct sockaddr *)(&adrClient), &adrSize)) == -1) { perror("accept"); return -1; } printf("New socket client : %s\n", inet_ntoa(adrClient.sin_addr)); do { // Read a msg from client if((lenMsg = recv(sockClient, message, 256, 0)) == -1) { perror("recv"); return -1; } message[lenMsg] = '\0'; printf("New msg received : %s\n", message); //printf("New msg received : %s, %d\n", message, strcmp(message, overMsg)); }while(strcmp(message, overMsg) != 0); // fermeture de la connexion close(sockServ); return 0; }
#include<stdio.h> #include<stdlib.h> #include<netinet/in.h> #include<sys/types.h> #include<unistd.h> #include<sys/socket.h> #include<string.h> void main(int argc, char* argv[]) { if(argc < 3) { printf("Syntax:%s server_addr <portNum>\n", argv[0]); exit(0); } int fdSock; //get a socket if( (fdSock=socket(AF_INET, SOCK_STREAM, 0)) == -1){perror("socket"); exit(1);} //config the address of the server to connect struct sockad