Windows系统下c++具体代码实现采用非阻塞模式实现面向连接的 socket 编程
时间: 2023-06-01 09:01:41 浏览: 172
以下是Windows系统下C语言非阻塞模式实现面向连接的socket编程的示例代码:
1. 创建socket
```c
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == INVALID_SOCKET) {
printf("Error creating socket: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
```
2. 设置非阻塞模式
```c
unsigned long mode = 1;
int result = ioctlsocket(sock, FIONBIO, &mode);
if (result != NO_ERROR) {
printf("Error setting non-blocking mode: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}
```
3. 连接服务器
```c
struct sockaddr_in server_address;
memset(&server_address, 0, sizeof(server_address));
server_address.sin_family = AF_INET;
server_address.sin_port = htons(port);
InetPton(AF_INET, server_ip, &server_address.sin_addr);
result = connect(sock, (struct sockaddr*)&server_address, sizeof(server_address));
if (result == SOCKET_ERROR && WSAGetLastError() != WSAEWOULDBLOCK) {
printf("Error connecting to server: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}
```
4. 使用select函数等待连接完成
```c
fd_set write_fds;
FD_ZERO(&write_fds);
FD_SET(sock, &write_fds);
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
result = select(0, NULL, &write_fds, NULL, &timeout);
if (result == 0) {
printf("Connection timed out.\n");
closesocket(sock);
WSACleanup();
return 1;
} else if (result == SOCKET_ERROR) {
printf("Error waiting for connection: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}
```
5. 发送数据
```c
const char* message = "Hello, server!";
result = send(sock, message, strlen(message), 0);
if (result == SOCKET_ERROR) {
printf("Error sending data: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}
```
6. 接收数据
```c
char buffer[1024];
result = recv(sock, buffer, sizeof(buffer), 0);
if (result == SOCKET_ERROR) {
printf("Error receiving data: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
} else {
buffer[result] = '\0';
printf("Received data: %s\n", buffer);
}
```
7. 关闭socket
```c
closesocket(sock);
WSACleanup();
```
阅读全文