首页 > 代码库 > 【网络编程笔记】简单的TCP协议 socket编程(C语言版服务器和客户端)

【网络编程笔记】简单的TCP协议 socket编程(C语言版服务器和客户端)

下图是一般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);   //socket11     gethostname(Server_name, 128);12     hp = gethostbyname(Server_name);           //获取本机名13     printf("本机名 : %s\n", 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!\n");23         //exit(1);24     }25     else26     {27         printf("绑定 socket success...\n");28     }29     listen(sockfd, 5);     //listening...监听30     printf("服务器监听状态...\n");31 32     ZeroMemory((void *)&addrtemp, sizeof(addrtemp));33     nlen = sizeof(addrtemp);34     connfd = accept(sockfd, &addrtemp, &nlen);  //accept...三次握手35     printf("accept client success...\n\n");36 }

客户端的建立:

     其实客户端和服务器代码都差不多的,只是最后面的一个connect()函数,就是发送一个请求链接给服务器,因为服务器在accept()函数时阻塞等待客户端的链接,然后经过三次握手,成功之后,服务器和客户端就可以进行通信了。

 1 WSAStartup(0x202, &wsaData); 2 if( (sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0 ) //socket... 3 { 4     printf("socket error!\n"); 5     exit(1); 6 }     7 gethostname(Server_name, 128); 8 host = gethostbyname(Server_name);        //获取本机名 9 printf("本机名 : %s\n", Server_name);10 11 memset(&addrServer, 0, sizeof(addrServer)); //初始化12 memcpy(&(addrServer.sin_addr), host->h_addr, host->h_length); //设置ip13 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!\n");20     exit(1);21 }22 printf("连接服务器成功connec success...\n\n");

接下来是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 !\n"); 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!\n");6     exit(1);7 }8 printf("recvbytes = %d\n", recvbytes);9 printf("recv from client : %s\n", recvBuf);

参考原文:http://blog.csdn.net/shiren_bod/article/details/6647022

 

【网络编程笔记】简单的TCP协议 socket编程(C语言版服务器和客户端)