首先,需要包含 winsock2.h
頭文件,并鏈接 ws2_32.lib
庫文件。
然后,可以按照以下步驟使用Winsock通過TCP發(fā)送數(shù)據(jù)段:
WSAStartup
函數(shù)來完成初始化。WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
// 初始化失敗
return -1;
}
socket
函數(shù)創(chuàng)建一個套接字,指定協(xié)議族為 AF_INET
,類型為 SOCK_STREAM
,協(xié)議為 IPPROTO_TCP
。SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
// 創(chuàng)建套接字失敗
WSACleanup();
return -1;
}
sockaddr_in
結(jié)構(gòu)體來設(shè)置服務(wù)器的地址和端口號。sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(12345); // 設(shè)置服務(wù)器端口號
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); // 設(shè)置服務(wù)器IP地址
connect
函數(shù)來連接到服務(wù)器。if (connect(clientSocket, (sockaddr*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) {
// 連接失敗
closesocket(clientSocket);
WSACleanup();
return -1;
}
send
函數(shù)來發(fā)送數(shù)據(jù)段。const char* data = "Hello, Server!";
int dataLength = strlen(data);
int bytesSent = send(clientSocket, data, dataLength, 0);
if (bytesSent == SOCKET_ERROR) {
// 發(fā)送失敗
closesocket(clientSocket);
WSACleanup();
return -1;
}
closesocket
函數(shù)來關(guān)閉連接。closesocket(clientSocket);
WSACleanup
函數(shù)來清理 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;
}
// 創(chuàng)建套接字
SOCKET clientSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (clientSocket == INVALID_SOCKET) {
std::cout << "Failed to create socket" << std::endl;
WSACleanup();
return -1;
}
// 設(shè)置服務(wù)器的地址信息
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(12345); // 設(shè)置服務(wù)器端口號
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1"); // 設(shè)置服務(wù)器IP地址
// 連接到服務(wù)器
if (connect(clientSocket, (sockaddr*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) {
std::cout << "Failed to connect to server" << std::endl;
closesocket(clientSocket);
WSACleanup();
return -1;
}
// 發(fā)送數(shù)據(jù)段
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;
}
// 關(guān)閉連接
closesocket(clientSocket);
// 清理 Winsock 庫
WSACleanup();
return 0;
}