C语言实现网络断开与重连的代码
时间: 2023-12-10 07:38:46 浏览: 188
c#socket断开重连
4星 · 用户满意度95%
下面是一个简单的 C 语言代码示例,用于检测网络连接状态并在发现断开连接时重新连接:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netdb.h>
#include <signal.h>
#define SERVER_ADDR "127.0.0.1"
#define SERVER_PORT 8080
#define MAX_BUF_SIZE 1024
int sockfd;
void sig_handler(int signo) {
if (signo == SIGINT) {
printf("Received SIGINT signal, closing socket and exiting...\n");
close(sockfd);
exit(0);
}
}
int connect_to_server() {
struct sockaddr_in servaddr;
int sock = socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
perror("socket error");
return -1;
}
memset(&servaddr, 0, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERVER_PORT);
if (inet_pton(AF_INET, SERVER_ADDR, &servaddr.sin_addr) <= 0) {
perror("inet_pton error");
return -1;
}
if (connect(sock, (struct sockaddr *)&servaddr, sizeof(servaddr)) == -1) {
perror("connect error");
return -1;
}
return sock;
}
int main(int argc, char *argv[]) {
signal(SIGINT, sig_handler);
char buf[MAX_BUF_SIZE];
int n;
sockfd = connect_to_server();
while (1) {
if (sockfd == -1) {
printf("Connection lost, retrying in 5 seconds...\n");
sleep(5);
sockfd = connect_to_server();
continue;
}
n = read(sockfd, buf, MAX_BUF_SIZE);
if (n == -1) {
perror("read error");
close(sockfd);
sockfd = -1;
continue;
}
if (n == 0) {
printf("Connection closed by server, retrying in 5 seconds...\n");
close(sockfd);
sockfd = -1;
sleep(5);
continue;
}
printf("Received %d bytes from server: %s\n", n, buf);
}
return 0;
}
```
这个代码示例中,我们使用了 `socket`、`connect`、`read` 函数连接到服务器并不断读取数据。如果连接断开,我们会在 5 秒后尝试重新连接。如果服务器关闭了连接,我们也会在 5 秒后尝试重新连接。当我们收到 SIGINT 信号时,我们会关闭套接字并退出程序。
你需要根据你的实际需求进行修改,并根据你的操作系统和编译器来编译和运行代码。
阅读全文