下图是一般socket 编程图。
服务器的建立:
获取的本机名,用来解析得到本机的IP地址的;接着就绑定IP地址成功,然后服务器就处于监听状态,等待客户端的连接。也就是接下来就是TCP/IP的三次握手的操作,该操作成功了服务器和客户端就可以进行通信了。以下是注释代码:
1 void socketConnect() 2 { 3 char Server_name[128]; 4 WSADATA wsaData; 5 struct hostent *hp; 6 struct sockaddr_in addrServer; 7 8 WSAStartup(0x202, &wsaData); 9 10 sockfd = socket(AF_INET, SOCK_STREAM, 0); //socket 11 gethostname(Server_name, 128); 12 hp = gethostbyname(Server_name); //获取本机名 13 printf("本机名 : %s ", Server_name); 14 15 memset(&addrServer, 0, sizeof(addrServer)); //初始化 16 memcpy(&(addrServer.sin_addr), hp->h_addr, hp->h_length); //设置服务器的IP地址 17 addrServer.sin_family = AF_INET; //设置版本 18 addrServer.sin_port = htons((unsigned short)SERVER_PORT); //设置端口号 19 //bind....绑定ip地址和端口号 20 if(SOCKET_ERROR == bind(sockfd, (LPSOCKADDR)&addrServer, sizeof(addrServer))) 21 { 22 printf("Bind socket error! "); 23 //exit(1); 24 } 25 else 26 { 27 printf("绑定 socket success... "); 28 } 29 listen(sockfd, 5); //listening...监听 30 printf("服务器监听状态... "); 31 32 ZeroMemory((void *)&addrtemp, sizeof(addrtemp)); 33 nlen = sizeof(addrtemp); 34 connfd = accept(sockfd, &addrtemp, &nlen); //accept...三次握手 35 printf("accept client success... "); 36 }
客户端的建立:
其实客户端和服务器代码都差不多的,只是最后面的一个connect()函数,就是发送一个请求链接给服务器,因为服务器在accept()函数时阻塞等待客户端的链接,然后经过三次握手,成功之后,服务器和客户端就可以进行通信了。
1 WSAStartup(0x202, &wsaData); 2 if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) //socket... 3 { 4 printf("socket error! "); 5 exit(1); 6 } 7 gethostname(Server_name, 128); 8 host = gethostbyname(Server_name); //获取本机名 9 printf("本机名 : %s ", Server_name); 10 11 memset(&addrServer, 0, sizeof(addrServer)); //初始化 12 memcpy(&(addrServer.sin_addr), host->h_addr, host->h_length); //设置ip 13 addrServer.sin_family = AF_INET; //设置版本号 14 addrServer.sin_port = htons((unsigned short)SERVER_PORT); //设置端口号 15 16 //connect....向服务器发起链接 17 if(connect(sockfd, (struct sockaddr *)&addrServer, sizeof(struct sockaddr))) 18 { 19 printf("connect error! "); 20 exit(1); 21 } 22 printf("连接服务器成功connec success... ");
接下来是send()和recv()函数:
1 //send...发送消息 2 scanf("%s", sendBuf); 3 getchar(); 4 5 if( (sendbytes = send(connfd, sendBuf, strlen(sendBuf), 0)) <= 0) 6 { 7 printf("send error ! "); 8 continue; 9 } 10 memset(sendBuf, 0, sizeof(sendBuf));
1 //recv...接收消息 2 memset(recvBuf, 0, sizeof(recvBuf)); 3 if( (recvbytes = recv(connfd, recvBuf, sizeof(recvBuf), 0)) <= 0) 4 { 5 printf("recv error! "); 6 exit(1); 7 } 8 printf("recvbytes = %d ", recvbytes); 9 printf("recv from client : %s ", recvBuf);
参考原文:http://blog.csdn.net/shiren_bod/article/details/6647022