基于C++简单Windows API的socket编程(阻塞模式)

来源:互联网 发布:矢量图软件 手机版 编辑:程序博客网 时间:2024/06/05 07:02

1. 概述:简单的基于Windows API的socket点对点聊天程序,为了方便初学者,本文代码均采用阻塞原理编写。


2. 代码样例


Server.cpp(服务端)


#include <cstdio>#include <cstdlib>#include <iostream>#define WIN32_LEAN_AND_MEAN#include <windows.h>#include <Winsock2.h>using namespace std;#pragma comment(lib,"ws2_32.lib")const short HOST_PORT = 4500;const char *HOST_IP = "127.0.0.1";int main(void){int maxConnectTimeout = 20; char revData[255] = "\0";sockaddr_in sain;sockaddr_in remote_sain;SOCKET sClient;SOCKET sServer;WSADATA wsaData;int remoteLen = sizeof(remote_sain);WORD sockVersion = MAKEWORD(2,2);if (WSAStartup(sockVersion,&wsaData) != 0){return 0;}sServer = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if (sServer == INVALID_SOCKET){printf("[-] SOCKET CREATE ERROR\n");return 0;}else{printf("[*] SOCKET CREATE SUCCESS\n");}sain.sin_family = AF_INET;sain.sin_port = htons(HOST_PORT);sain.sin_addr.S_un.S_addr = INADDR_ANY;if (bind(sServer,(SOCKADDR*)&sain,sizeof(sain)) == SOCKET_ERROR){printf("[-]CANNOT BIND\n");return 0;}else{printf("[*]BIND SUCCESS\n");}if (listen(sServer,5) == SOCKET_ERROR){printf("[-]LISTENING ERROR\n");return 0;}else{printf("[*]LISTENING SUCCESS\n");}while(1){printf("\n[*]Listening Remote-PC ...\n\n");sClient = accept(sServer,(SOCKADDR*)&remote_sain,&remoteLen); if (sClient == INVALID_SOCKET) {printf("[-]SOCKET RECV ERROR ..."); continue; }printf("[+]PC from %s \n",inet_ntoa(remote_sain.sin_addr));while (1){int ret = recv(sClient,revData,255,0);if (ret > 0){revData[ret] ='\0';printf("%s\n",revData);}}closesocket(sClient);break;}printf("[-]Server OFF!");closesocket(sServer);WSACleanup();return 0;}


Client.cpp(客户端)


#include <cstdio>#include <cstdlib>#include <iostream>#define WIN32_LEAN_AND_MEAN#include <windows.h>#include <Winsock2.h>using namespace std;#pragma comment(lib,"ws2_32.lib")const short HOST_PORT = 4500;const char *HOST_IP = "127.0.0.1";int main(void){int Recvret = 0;char Sendbuff[255] = "\0";char Recvbuff[255] = "\0";WSADATA wsData;WORD sockVersion = MAKEWORD(2,2);sockaddr_in Remote_sain;if (WSAStartup(sockVersion,&wsData) != 0){printf("[-]SOCKET STARTUP ERROR\n");return 0;}else{printf("[*]SOCKET STARTUP SUCCESS\n");}SOCKET sClient = socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);if (sClient == INVALID_SOCKET){printf("[-]SOCKET CREATE ERROR\n");return 0;}else{printf("[*]SOCKET CREATE SUCCESS\n");}Remote_sain.sin_addr.S_un.S_addr = inet_addr(HOST_IP);Remote_sain.sin_port = htons(HOST_PORT);Remote_sain.sin_family = AF_INET;if (connect(sClient,(SOCKADDR*)&Remote_sain,sizeof(Remote_sain)) == SOCKET_ERROR){printf("[-]Can not connect to the Server\n");closesocket(sClient);return 0;}else{printf("[*]Listening to %s:%d ...OK\n",HOST_IP,HOST_PORT);}while (1){if (Recvret = recv(sClient,Recvbuff,255,0) != 0){Recvbuff[Recvret] = '\0';printf("[*]Server(%s):\n",HOST_IP);}gets(Sendbuff);send(sClient,Sendbuff,255,0);printf("[*]Client:%s\n",Sendbuff);}closesocket(sClient);return 0;}


原创粉丝点击