Server:
#include<Winsock2.h> #include<stdio.h> #include<stdlib.h> #define PORT 5000 void main() { // 打开 Winsock,服务以 动态链接库 实现 WSADATA wsaData; if( WSAStartup(MAKEWORD(2,2) , &wsaData )!=0 ){ // 0表示成功 printf("Winsock load failed/n"); return ; } // 创建 监听套接口,流式套接口 SOCKET sListen=socket(AF_INET,SOCK_STREAM,0); if(sListen==INVALID_SOCKET){ printf("socket failed:%d/n",WSAGetLastError()); return; } // 服务器 地址 sockaddr_in serv; serv.sin_family=AF_INET; int port=PORT; serv.sin_port=htons(port); //端口16位 serv.sin_addr.s_addr=htonl(INADDR_ANY); //ip32位 // 绑定 if( bind(sListen,(LPSOCKADDR)&serv, sizeof(serv)) ==SOCKET_ERROR){ printf("bind() failed:%d/n",WSAGetLastError()); return ; } // 监听 if( listen(sListen,5)==SOCKET_ERROR ){ printf("listen() failed:%d/n",WSAGetLastError()); return ; } sockaddr_in client; int iLen=sizeof(client); while(true){ // 等待客户连接请求 SOCKET sAccept=accept(sListen, (sockaddr*)&client, &iLen); if(sAccept==SOCKET_ERROR){ printf("accept() failed:%d/n",WSAGetLastError()); break; ; } // 输出客户IP地址和端口 printf("accepted client IP:[%s],port:[%d]/n",inet_ntoa(client.sin_addr), ntohs(client.sin_port)); // 给客户发送信息 char buf[]=" HELLO, HOW ARE YOU!"; int iSend=send(sAccept,buf,sizeof(buf),0); if(iSend==SOCKET_ERROR){ printf("send() failed:%d/n",WSAGetLastError()); break; ; } else if(iSend==0) break; else printf("send() byte:%d/n",iSend); closesocket(sAccept); } closesocket(sListen); WSACleanup(); }
Client:
#include<Winsock2.h> #include<stdio.h> #include<stdlib.h> #define PORT 5000 #define BUFFER 1024 void main(int argc, char * argv[]) { // 打开 Winsock,服务以 动态链接库 实现 WSADATA wsaData; if( WSAStartup(MAKEWORD(2,2) , &wsaData )!=0 ){ // 0表示成功 printf("Winsock load failed/n"); return ; } // 服务器 地址 sockaddr_in server; server.sin_family=AF_INET; int port=PORT; server.sin_port=htons(port); server.sin_addr.s_addr=inet_addr("169.254.18.135"); // 创建 套接口 SOCKET clientSocket=socket(AF_INET, SOCK_STREAM,0); if(clientSocket==INVALID_SOCKET){ printf("socket() failed:%d/n",WSAGetLastError()); return; } // 连接服务器 if( connect(clientSocket, (sockaddr*)&server,sizeof(server) )==INVALID_SOCKET ){ printf("connect() failed:%d/n",WSAGetLastError()); return; } else { char buf[BUFFER]; int iLen=recv(clientSocket,buf,sizeof(buf),0); if(iLen==0) return; else if(iLen==SOCKET_ERROR){ printf("recv() failed:%d/n",WSAGetLastError()); return; } else printf("recv() data from server :%s/n",buf); } closesocket(clientSocket); WSACleanup(); system("pause"); }