服务器端:
#include <iostream> #include <WinSock2.h> #pragma comment(lib, "ws2_32.lib") void main() { //1 初始化阶段 WORD wVer; WSADATA wsaData; wVer = MAKEWORD(1,1); WSAStartup(wVer,&wsaData); //2 建立Socket SOCKET mySocket = socket(AF_INET,SOCK_STREAM,0); SOCKADDR_IN sockAddr; sockAddr.sin_family = AF_INET; sockAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY); sockAddr.sin_port =htons(6000); //3 绑定端口 bind(mySocket,(SOCKADDR*)&sockAddr,sizeof(SOCKADDR)); //4 监听 listen(mySocket,5); //5 等待客户端 SOCKADDR_IN sockInAddr; int len = sizeof(SOCKADDR); while (1) { printf("I'm watting for you.\n"); SOCKET sockIn = accept(mySocket,(SOCKADDR*)&sockInAddr,&len); char buf[50]; memset(buf,0,sizeof(buf)); sprintf(buf,"Hello, %s .I'm your sever!",inet_ntoa(sockInAddr.sin_addr)); send(sockIn,buf,strlen(buf)+1,0); char bufRecv[50]; memset(bufRecv,0,sizeof(bufRecv)); recv(sockIn,bufRecv,sizeof(bufRecv),0); printf(bufRecv); } }客户端:
#include <stdio.h> #include <Winsock2.h> #pragma comment(lib, "ws2_32.lib") void main() { //1 初始化阶段 WORD wVersionRequested; WSADATA wsaData;//WSAata用来存储系统传回的关于WinSocket的资料。 int err; wVersionRequested = MAKEWORD( 1, 1 ); err = WSAStartup( wVersionRequested, &wsaData ); if ( err != 0 ) { return; } if ( LOBYTE( wsaData.wVersion ) != 1 ||HIBYTE( wsaData.wVersion ) != 1 ) { WSACleanup( ); return; } //2 建立socket SOCKET sockClient=socket(AF_INET,SOCK_STREAM,0);// AF_INET ..tcp连接 //初始化连接与端口号 SOCKADDR_IN addrSrv; addrSrv.sin_addr.S_un.S_addr=inet_addr("127.0.0.1");//本机地址,服务器在本机开启 addrSrv.sin_family=AF_INET; addrSrv.sin_port=htons(6000);// 设置端口号 //3 连接服务端 connect(sockClient,(SOCKADDR*)&addrSrv,sizeof(SOCKADDR));//连接服务器 char recvBuf[50]; //4 接收数据 if(recv(sockClient,recvBuf,50,0) == SOCKET_ERROR )//接受数据 //发送数据 send(sockClient,"hello",strlen("hello")+1,0);//发送数据 closesocket(sockClient);//关闭连接 WSACleanup(); system("PAUSE"); }