1 #include<winsock2.h>//winsock的头文件 2 #include<iostream> 3 4 using namespace std; 5 6 //指定动态库的lib文件 7 #pragma comment(lib,"ws2_32.lib") 9 //TCP客户端 10 int main() 11 { 12 13 //初始化winsock2.2相关的动态库 14 WSADATA wd;//获取socket相关信息 15 if (WSAStartup(MAKEWORD(2, 2), &wd) != 0)//0表示成功 16 { 17 cout << "WSAStartup error:" << WSAGetLastError() << endl; 18 return 0; 19 } 20 21 22 //1.创建TCP socket , 流式套接字 23 SOCKET s = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); 24 if (s == INVALID_SOCKET) 25 { 26 cout << "socket error:" << WSAGetLastError() << endl; 27 return 0; 28 } 29 30 //2.链接服务端 31 sockaddr_in addr;//不建议使用sockaddr,建议用sockaddr_in 32 addr.sin_port = htons(6000);//网络字节序 33 addr.sin_addr.S_un.S_addr = inet_addr("127.0.0.1");//网络字节序 34 addr.sin_family = AF_INET; //地址族 35 int len = sizeof(sockaddr_in); 36 37 if (connect(s, (sockaddr*)&addr, len) == SOCKET_ERROR) 38 { 39 cout << "connect error:" << WSAGetLastError() << endl; 40 return 0; 41 } 42 43 //3.接受发送消息 44 int ret = 0; 45 do 46 { 47 //接受客户端的消息 48 char buf[64] = { '' }; 49 ret = recv(s, buf, 64, 0);//把flag置0 50 cout << "recv" << inet_ntoa(addr.sin_addr) << ": " << buf << endl;// inet_ntoa转换为IP字符串 51 52 //发送 53 ret = send(s, "I am Client!", strlen("I am Client!"), 0); 54 55 Sleep(1000); 56 } while (ret != SOCKET_ERROR && ret != 0); 57 58 59 //4.关闭套接字 60 closesocket(s); 61 62 //清理winsock环境 63 WSACleanup(); 64 65 66 return 0; 67 }
注意报错处理方式:
https://blog.csdn.net/u010257002/article/details/45393463