Service side:
1 #define_crt_secure_no_warnings2 3#include <stdio.h>4#include <winsock2.h>5 #pragmaComment (lib, "Ws2_32.lib")6 7 /*8 TCP Service Side9 */Ten intMainvoid) One { A intLen =0; - wsadata WD; - intRET =0; the SOCKET S, c; - Charsendbuf[ +] ="", recvbuf[ +] =""; - sockaddr_in saddr, caddr; -ret = WSAStartup (Makeword (2,2), &WD);/*1. Initialize the Operation*/ + - if(Ret! =0) + { A return 0; at } - if(Hibyte (wd.wversion)! =2|| Lobyte (wd.wversion)! =2) - { -printf"initialization failed"); - WSACleanup (); - return 1; in } - to /*2. Create a service-side socket*/ +s = socket (af_inet, Sock_stream,0); - the /*3. Set up service-side information*/ *Saddr.sin_addr. S_un. S_ADDR =htonl (inaddr_any); $saddr.sin_family = af_inet;/*protocol Type*/Panax NotoginsengSaddr.sin_port = htons (8888); - the /*4. Binding on the local port*/ +Bind (S, (SOCKADDR *) &saddr,sizeof(SOCKADDR)); A the /*5. Listening Port*/ +Listen (s),5); - $Len =sizeof(sockaddr); $ - while(1) - { the /*6. Wait for the client to connect, which will block here until a client connection arrives. */ -C = Accept (S, (sockaddr*) &caddr, &len);Wuyi thesprintf (SendBuf,"Welcome to my first socket, your IP address is:%s\n", Inet_ntoa (CADDR.SIN_ADDR)); - Wu /*7. Sending data to the client*/ -Send (c, SendBuf, strlen (SENDBUF) +1,0); About $ /*8. Accept the return of the client*/ -Recv (c, Recvbuf, +,0); - - /*9. Print out the data sent by the client*/ Aprintf"%s\n", recvbuf); + the /*10. If you are no longer contacting this client, close it*/ - closesocket (c); $ } the /*If there is a condition to exit the loop, the use of the socket library needs to be cleared*/ the /*WSACleanup ();*/ the return 0; the}
Client:
1 #define_crt_secure_no_warnings2 3#include <stdio.h>4#include <winsock2.h>5 #pragmaComment (lib, "Ws2_32.lib")6 7 intMainvoid)8 {9 wsadata WD;Ten intRET =0; One SOCKET C; A Charrecvbuf[ +] ="", sendbuf[ +] =""; - sockaddr_in saddr; -ret = WSAStartup (Makeword (2,2), &WD);/*1. Initialize the Operation*/ the - if(Ret! =0) - { - return 0; + } - + if(Hibyte (wd.wversion)! =2|| Lobyte (wd.wversion)! =2) A { atprintf"initialization failed"); - WSACleanup (); - return 1; - } - - /*2. Create a client socket*/ inc = Socket (Af_inet, Sock_stream,0); - to /*3. Define the service-side information to be connected*/ +Saddr.sin_addr. S_un. S_ADDR = inet_addr ("127.0.0.1"); -saddr.sin_family =af_inet; theSaddr.sin_port = htons (8888); * $ /*4. Connecting the service side*/Panax NotoginsengConnect (c, (sockaddr*) &saddr,sizeof(SOCKADDR)); -Recv (c, Recvbuf, +,0); theprintf"data sent from the server:%s\n", recvbuf); + Asprintf (SendBuf,"Service side Hello!!! "); theSend (c, SendBuf, strlen (SENDBUF) +1,0); + - closesocket (c); $ WSACleanup (); $ - GetChar (); - return 0; the}
C Language Socket Network programming example