C++网络编程实例(socket)
生活随笔
收集整理的這篇文章主要介紹了
C++网络编程实例(socket)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
C++網絡編程實例(socket)
功能
實現基于sokcet的Cpp服務端
TIPS:功能包括接收客戶端的數據,向客戶端發送數據。
源碼
#define _WINSOCK_DEPRECATED_NO_WARNINGS #include <iostream> //#include <windows.h> #include <WinSock2.h> #pragma comment(lib,"ws2_32") using std::cout; using std::endl; using std::cin;int main() {system("chcp 65001");//SetConsoleOutputCP(65001);WSADATA wsaData;WSAStartup(MAKEWORD(2, 2), &wsaData);//啟動window動態網絡庫//1.創建socket//SOCKET == 句柄 == 文件描述符 == 套接字//socket(協議族類型,協議類型,0);//協議族類型 IPV4(AF_INET) IPV6//協議類型 TCP(SOCK_STREAM),UDP(SOCK_DROP)SOCKET serverSocket = socket(AF_INET, SOCK_STREAM, 0);//IPPROTO_TCPif (serverSocket == INVALID_SOCKET){cout << "創建socket失敗" << endl;return 0;}//2.綁定ip和端口號//127.0.0.1 永遠指向本機//0.0.0.o 綁定所有網卡的ipSOCKADDR_IN serverAddr;serverAddr.sin_family = AF_INET;serverAddr.sin_port = htons(7890);//host to networks short,將主機字節序轉化為網絡字節序serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");//點分十進制轉換為10進制if (SOCKET_ERROR == bind(serverSocket, (sockaddr *)&serverAddr, sizeof(SOCKADDR_IN))){cout << "bind 失敗" << endl;return 0;}cout << "bind 成功" << endl;//3.監聽,提示本機的操作系統if (INVALID_SOCKET == listen(serverSocket, 5)){cout << "listen 失敗" << endl;return 0;}cout << "listen 成功" << endl;while(true){//4.等待客戶端連接SOCKADDR_IN clientAddr;int addrLen = sizeof(SOCKADDR_IN);SOCKET clientSocket = accept(serverSocket, (SOCKADDR *)&clientAddr, &addrLen);if (INVALID_SOCKET == clientSocket){cout << "客戶端連接失敗 " << endl;return 0;}cout << "client ok " << inet_ntoa(clientAddr.sin_addr) << endl;cout << "port " << ntohs(clientAddr.sin_port) << endl;//5.收發數據//接收數據char recvBuffer[1024]{ 0 };int nRecv = recv(clientSocket, recvBuffer, 1024, 0);cout << "recvLen:" << nRecv << "內容:" << recvBuffer << endl;//發送數據int nSend = send(clientSocket, recvBuffer, nRecv, 0);cout << "send Len:" << nSend << endl;//6.關閉客戶端closesocket(clientSocket);}//7.關閉服務端closesocket(serverSocket);WSACleanup();//卸載window動態網絡庫return 0; }效果
TIPS:利用sokit模擬工具模擬一個客戶端終端。
總結
以上是生活随笔為你收集整理的C++网络编程实例(socket)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: weblogic部署项目后内存溢出
- 下一篇: Java 移位运算符