vs2019 socket tcp客户端连接代码
时间: 2023-10-04 14:05:00 浏览: 93
以下是一个基本的TCP客户端连接代码示例,使用Visual Studio 2019和C++编写。
```c++
#include <iostream>
#include <winsock2.h>
#pragma comment (lib, "ws2_32.lib")
int main() {
// 初始化Winsock库
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
std::cout << "WSAStartup failed: " << result << std::endl;
return 1;
}
// 创建socket
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
std::cout << "Failed to create client socket: " << WSAGetLastError() << std::endl;
WSACleanup();
return 1;
}
// 填写服务器地址和端口号
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); // 服务器IP地址
serverAddress.sin_port = htons(12345); // 服务器端口号
// 连接服务器
result = connect(clientSocket, (SOCKADDR*)&serverAddress, sizeof(serverAddress));
if (result == SOCKET_ERROR) {
std::cout << "Failed to connect to server: " << WSAGetLastError() << std::endl;
closesocket(clientSocket);
WSACleanup();
return 1;
}
// 连接成功,可以进行通信了
char buffer[1024];
result = recv(clientSocket, buffer, sizeof(buffer), 0);
if (result == SOCKET_ERROR) {
std::cout << "Failed to receive data from server: " << WSAGetLastError() << std::endl;
closesocket(clientSocket);
WSACleanup();
return 1;
}
buffer[result] = '\0';
std::cout << "Received message from server: " << buffer << std::endl;
// 关闭socket,释放资源
closesocket(clientSocket);
WSACleanup();
return 0;
}
```
此代码使用Windows套接字API来创建一个TCP客户端,连接到指定的服务器地址和端口。如果连接成功,则从服务器接收数据并在控制台上输出。最后,关闭套接字和清理资源。注意在使用Windows套接字API时需要调用`WSAStartup()`和`WSACleanup()`函数来初始化和释放Winsock库。
阅读全文