- 创建VS工程
- 配置
- 属性页-链接器-输入-附加依赖项,添加:ws2_32.lib
- heads.h
1 2 3 4 5 6 7 8 9 |
#pragma once //避免宏的重复引用 #define WIN32_LEAN_AND_MEAN //使用到inet_ntoa #define _SOCKET_DEPRECATED_NO_WARNINGS #include <WinSocket2.h> #include <Windows.h> #include <iostream> using namespace std; |
- client.cpp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
int main() { const WORD socket_ver = MAKEWORD(2, 2);//使用2.2socket WSADATA dat; auto start_result = WSAStartup(socket_ver, &dat);//启动socket //1.socket //ipv4;数据流; SOCKET client_sock = socket(AF_INET,SOCK_STREAM,0); if (client_sock == INVALID_SOCKET) { cout << "Client socket created failed!!!" << endl; return Aet::Error_exit; } else cout << "Client socket created success..." << endl; //2.连接服务器 sockaddr_in _sin{}; _sin.sin_family = AF_INET; _sin.sin_port = htons(4567); string ip("127.0.0.1"); inet_pton(AF_INET, ip.c_str(), &_sin.sin_addr.S_un.S_addr); auto ret = connect(client_sock, reinterpret_cast<const sockaddr*>(&_sin), sizeof(sockaddr_in)); if(ret == SOCKET_ERROR) { cout << "Client connect failed!!!" << endl; return Aet::Error_exit; } //3.输入命令 char cmdBuf[128] = {}; while (true) { cin >> cmdBuf; send(client_sock, cmdBuf, 128, 0);//5.发送请求 if(strcmp(cmdBuf,"exit") == 0)//4.处理请求 { cout << "Exit the program..." << endl; return Aet::Error_exit; } else { //6.接收数据 char msgBuff[256] = {}; auto length = recv(client_sock, msgBuff, 256, 0); if (length > 0) { cout << "The msg is:" << msgBuff << endl; } } } //7.closesocke if (closesocket(client_sock) == NULL) cout << "Socket close success..." << endl; WSACleanup(); system("pause"); return 0; } |
本文为原创文章,版权归Aet所有,欢迎分享本文,转载请保留出处!
你可能也喜欢
- ♥ Socket:相关记述11/09
- ♥ 51CTO:C++网络通信引擎架构与实现一09/09
- ♥ Socket:创建TCP服务端10/17
- ♥ Socket基础:TCP篇10/16
- ♥ 创建socket环境:hello socket10/16
- ♥ Socket:发送结构化消息-结构体10/19