首先,需要包含 winsock2.h
头文件,并链接 ws2_32.lib
库文件。
然后,可以按照以下步骤使用Winsock通过TCP发送数据段:
WSAStartup
函数来完成初始化。WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
// 初始化失败
return -1;
}
socket
函数创建一个套接字,指定协议族为 AF_INET
,类型为 SOCK_STREAM
,协议为 IPPROTO_TCP
。SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
// 创建套接字失败
WSACleanup();
return -1;
}
sockaddr_in
结构体来设置服务器的地址和端口号。sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(12345); // 设置服务器端口号
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); // 设置服务器IP地址
connect
函数来连接到服务器。if (connect(clientSocket, (sockaddr*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) {
// 连接失败
closesocket(clientSocket);
WSACleanup();
return -1;
}
send
函数来发送数据段。const char* data = "Hello, Server!";
int dataLength = strlen(data);
int bytesSent = send(clientSocket, data, dataLength, 0);
if (bytesSent == SOCKET_ERROR) {
// 发送失败
closesocket(clientSocket);
WSACleanup();
return -1;
}
closesocket
函数来关闭连接。closesocket(clientSocket);
WSACleanup
函数来清理 Winsock 库。WSACleanup();
完整的例子代码如下:
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
int main() {
// 初始化 Winsock 库
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cout << "Failed to initialize Winsock" << std::endl;
return -1;
}
// 创建套接字
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
std::cout << "Failed to create socket" << std::endl;
WSACleanup();
return -1;
}
// 设置服务器的地址信息
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(12345); // 设置服务器端口号
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); // 设置服务器IP地址
// 连接到服务器
if (connect(clientSocket, (sockaddr*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) {
std::cout << "Failed to connect to server" << std::endl;
closesocket(clientSocket);
WSACleanup();
return -1;
}
// 发送数据段
const char* data = "Hello, Server!";
int dataLength = strlen(data);
int bytesSent = send(clientSocket, data, dataLength, 0);
if (bytesSent == SOCKET_ERROR) {
std::cout << "Failed to send data" << std::endl;
closesocket(clientSocket);
WSACleanup();
return -1;
}
// 关闭连接
closesocket(clientSocket);
// 清理 Winsock 库
WSACleanup();
return 0;
}