winsock2客户端代码
时间: 2023-07-09 15:51:39 浏览: 45
以下是一个简单的Winsock2客户端代码示例,它连接到服务器并发送消息:
```c++
#include <winsock2.h>
#include <ws2tcpip.h> // Windows Sockets Error Codes
#pragma comment(lib, "ws2_32.lib") // Link with ws2_32.lib library
int main() {
WSADATA wsaData;
int iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
printf("WSAStartup failed: %d\n", iResult);
return 1;
}
// Create a socket
SOCKET ConnectSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ConnectSocket == INVALID_SOCKET) {
printf("socket failed: %ld\n", WSAGetLastError());
WSACleanup();
return 1;
}
// Connect to the server
struct addrinfo* result = NULL, * ptr = NULL, hints;
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
iResult = getaddrinfo("localhost", "12345", &hints, &result);
if (iResult != 0) {
printf("getaddrinfo failed: %d\n", iResult);
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
iResult = connect(ConnectSocket, ptr->ai_addr, (int)ptr->ai_addrlen);
if (iResult == SOCKET_ERROR) {
closesocket(ConnectSocket);
ConnectSocket = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (ConnectSocket == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
// Send data to the server
const char* sendbuf = "Hello, Server!";
iResult = send(ConnectSocket, sendbuf, (int)strlen(sendbuf), 0);
if (iResult == SOCKET_ERROR) {
printf("send failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
printf("Bytes sent: %ld\n", iResult);
// Shutdown the connection since no more data will be sent
iResult = shutdown(ConnectSocket, SD_SEND);
if (iResult == SOCKET_ERROR) {
printf("shutdown failed: %d\n", WSAGetLastError());
closesocket(ConnectSocket);
WSACleanup();
return 1;
}
// Cleanup
closesocket(ConnectSocket);
WSACleanup();
return 0;
}
```
请注意,此代码仅用于演示目的,实际应用程序应该包括错误检查和处理,以及更复杂的数据传输逻辑。