目标:用c编写一个电脑端socket客户端,实现客户端与测试平台的连接
执行:
1、下载并安装vs2022
(Visual Studio: 面向软件开发人员和 Teams 的 IDE 和代码编辑器 (microsoft.com))
2、查询chatgpt,看看程序怎么写(https://chatgpt.com/)
3、因为博主对于c来说还是萌新,所以查询到程序后,查询如何使用vs2022
(如何用VS2022写C语言(萌新必看) - 哔哩哔哩 (bilibili.com))
4、debug的过程:
由于第一次gpt提供的程序仅适用于UNIX/Linux系统,因此修改提问方式,添加windows系统的前提;
添加前提后的回答是适用于windows系统的c程序,但是系统报错“C4996 'inet_addr': Use inet_pton() or InetPton() instead or define _WINSOCK_DEPRECATED_NO_WARNINGS to disable deprecated API warnings”,这个错误提示表明 inet_addr
函数在Windows平台上已被标记为过时,可以使用 InetPton
(IPv4和IPv6的兼容版本)或者 inet_pton
(只兼容IPv4)代替inet_addr
。使用 InetPton
函数替换 inet_addr
后程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h> // 包含InetPton函数
// 链接Winsock库
#pragma comment(lib, "ws2_32.lib")
#define HOST "cptest.axxc.cn"
#define PORT 30020
int main() {
WSADATA wsa;
SOCKET sock;
struct sockaddr_in server;
char buffer[1024];
int bytes_received;
// 初始化Winsock
printf("Initializing Winsock...\n");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed. Error Code : %d\n", WSAGetLastError());
return 1;
}
printf("Initialized.\n");
// 创建Socket
if ((sock = socket(AF_INET, SOCK_STREAM, 0)) == INVALID_SOCKET) {
printf("Could not create socket : %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
printf("Socket created.\n");
// 设置服务器地址
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
if (InetPton(AF_INET, HOST, &server.sin_addr) <= 0) {
printf("Invalid address or Address not supported\n");
closesocket(sock);
WSACleanup();
return 1;
}
// 连接到远程服务器
if (connect(sock, (struct sockaddr*)&server, sizeof(server)) < 0) {
printf("Connection failed: %d\n", WSAGetLastError());
closesocket(sock);
WSACleanup();
return 1;
}
printf("Connected to the server at %s:%d\n", HOST, PORT);
// 接收数据
while ((bytes_received = recv(sock, buffer, sizeof(buffer), 0)) > 0) {
buffer[bytes_received] = '\0';
printf("Received: %s\n", buffer);
}
if (bytes_received == SOCKET_ERROR) {
printf("recv failed: %d\n", WSAGetLastError());
}
else if (bytes_received == 0) {
printf("Server closed the connection\n");
}
// 关闭Socket并清理
closesocket(sock);
WSACleanup();
return 0;
}
因为本项目还有“hello world”文件也有main函数,所以再次报错。
一个项目只能有一个main!!!
一个项目只能有一个main!!!
一个项目只能有一个main!!!
删除“hello world”文件,再次运行:
至少没报错,下次研究程序是否实现了目标。
=========================================================================================================2024.08.22更新=============================
看输出结果,程序卡在了 “设置服务器地址” 这一步。该错误信息“Invalid address or Address not supported
”表明InetPton
函数无法正确解析主机名"cptest.axxc.cn"
,从而导致无法将其转换为IP地址。
==========================================================================================================2024.08.24更新============================
为了正确处理主机名,使用 getaddrinfo
函数来解析主机名为IP地址,然后使用 connect
函数连接到这个地址。新程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h> // 包含getaddrinfo函数
// 链接Winsock库
#pragma comment(lib, "ws2_32.lib")
#define HOST "cptest.axxc.cn"
#define PORT "30020"
int main() {
WSADATA wsa;
SOCKET sock;
struct addrinfo hints, * result, * ptr;
char buffer[1024];
int bytes_received;
// 初始化Winsock
printf("Initializing Winsock...\n");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed. Error Code : %d\n", WSAGetLastError());
return 1;
}
printf("Initialized.\n");
// 设置服务器地址信息
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET; // 使用IPv4
hints.ai_socktype = SOCK_STREAM; // 使用TCP协议
hints.ai_protocol = IPPROTO_TCP; // TCP协议
// 获取主机地址信息
if (getaddrinfo(HOST, PORT, &hints, &result) != 0) {
printf("getaddrinfo failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 尝试连接到返回的地址信息
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// 创建Socket
if ((sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == INVALID_SOCKET) {
printf("Could not create socket: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 连接到远程服务器
if (connect(sock, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR) {
closesocket(sock);
sock = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result); // 释放地址信息
if (sock == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
printf("Connected to the server at %s:%s\n", HOST, PORT);
// 接收数据
while ((bytes_received = recv(sock, buffer, sizeof(buffer), 0)) > 0) {
buffer[bytes_received] = '\0';
printf("Received: %s\n", buffer);
}
if (bytes_received == SOCKET_ERROR) {
printf("recv failed: %d\n", WSAGetLastError());
}
else if (bytes_received == 0) {
printf("Server closed the connection\n");
}
// 关闭Socket并清理
closesocket(sock);
WSACleanup();
return 0;
}
为了腾出main函数的位置,注释掉之前的程序(代码快速注释(快捷键)_一键注释-CSDN博客)。新程序运行结果如下:
至少无法解析主机名的问题解决了。
=======================================================================================================2024.08.25更新===============================
但此时仍然没有运行出“Received:xxxx”之类的结果,这表明程序可能已经成功连接到了测试平台 cptest.axxc.cn
的端口 30020,
然而程序在连接成功后没有接收到来自测试平台的数据。为了验证测试平台是否是当我发送信息后才会产生反应,我会在建立连接后向测试平台发送一段信息,程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#pragma comment(lib, "ws2_32.lib")
#define HOST "cptest.axxc.cn"
#define PORT "30020"
int main() {
WSADATA wsa;
SOCKET sock = INVALID_SOCKET;
struct addrinfo hints, * result, * ptr;
char buffer[1024];
int bytes_received;
// 初始化Winsock
printf("Initializing Winsock...\n");
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed. Error Code : %d\n", WSAGetLastError());
return 1;
}
printf("Initialized.\n");
// 设置服务器地址信息
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET; // 使用IPv4
hints.ai_socktype = SOCK_STREAM; // 使用TCP协议
hints.ai_protocol = IPPROTO_TCP; // TCP协议
// 获取主机地址信息
if (getaddrinfo(HOST, PORT, &hints, &result) != 0) {
printf("getaddrinfo failed: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 尝试连接到返回的地址信息
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
// 创建Socket
if ((sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == INVALID_SOCKET) {
printf("Could not create socket: %d\n", WSAGetLastError());
WSACleanup();
return 1;
}
// 连接到远程服务器
if (connect(sock, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR) {
closesocket(sock);
sock = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result); // 释放地址信息
if (sock == INVALID_SOCKET) {
printf("Unable to connect to server!\n");
WSACleanup();
return 1;
}
printf("Connected to the server at %s:%s\n", HOST, PORT);
// 尝试发送消息到服务器
const char* message = "Hello Server!";
if (send(sock, message, strlen(message), 0) < 0) {
printf("Send failed: %d\n", WSAGetLastError());
}
else {
printf("Message sent successfully.\n");
}
// 接收数据
while ((bytes_received = recv(sock, buffer, sizeof(buffer), 0)) > 0) {
buffer[bytes_received] = '\0';
printf("Received: %s\n", buffer);
}
if (bytes_received == SOCKET_ERROR) {
printf("recv failed: %d\n", WSAGetLastError());
}
else if (bytes_received == 0) {
printf("Server closed the connection\n");
}
// 关闭Socket并清理
closesocket(sock);
WSACleanup();
return 0;
}
运行结果如下图:
从结果可以看出信息发送成功,但依然没有收到平台的回复。
===================================================================================================2024.08.26日与2024.08.27日更新======================
由于作者想不到下一步如何进行,索性在浏览器站点栏输入“http://cptest.axxc.cn”,搜索结果如图
由此可知该测试平台是由lnmp一键安装包搭建的环境。
好吧,下面我修改一下要求:学习socket编程,编写一个电脑端socket客户端,实现客户端与测试平台的连接(cptest.axxc.cn:30020),连接功能作为一个独立的线程存在,另外建立一个线程进行连接的守护,在检测到连接断开时发起重新连接。
第一步:在原有的提问基础上将此次的要求输入给chatgpt,得到程序如下
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <process.h> // _beginthread, _endthread
#pragma comment(lib, "ws2_32.lib")
#define HOST "cptest.axxc.cn"
#define PORT "30020"
// 全局变量,用于线程间通信
SOCKET sock = INVALID_SOCKET;
volatile int isConnected = 0;
volatile int stopRequested = 0;
// 连接线程函数
void __cdecl connectionThread(void* arg) {
struct addrinfo hints, * result, * ptr;
while (!stopRequested) {
WSADATA wsa;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed to initialize Winsock. Error Code: %d\n", WSAGetLastError());
return;
}
// 设置服务器地址信息
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(HOST, PORT, &hints, &result) != 0) {
printf("getaddrinfo failed: %d\n", WSAGetLastError());
WSACleanup();
return;
}
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
if ((sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == INVALID_SOCKET) {
printf("Could not create socket: %d\n", WSAGetLastError());
WSACleanup();
return;
}
if (connect(sock, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR) {
closesocket(sock);
sock = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (sock == INVALID_SOCKET) {
printf("Unable to connect to server, retrying...\n");
WSACleanup();
Sleep(5000); // 5秒后重试
continue;
}
printf("Connected to the server at %s:%s\n", HOST, PORT);
isConnected = 1;
// 这里可以进行数据收发或其他操作
// 尝试发送消息到服务器
const char* message = "hello server!";
if (send(sock, message, strlen(message), 0) < 0) {
printf("send failed: %d\n", WSAGetLastError());
}
else {
printf("message sent successfully.\n");
}
// 连接断开处理
while (isConnected && !stopRequested) {
char buffer[1024];
int bytes_received = recv(sock, buffer, sizeof(buffer) - 1, 0);
if (bytes_received == SOCKET_ERROR || bytes_received == 0) {
printf("Connection lost, attempting to reconnect...\n");
isConnected = 0;
closesocket(sock);
WSACleanup();
break;
}
buffer[bytes_received] = '\0';
printf("Received: %s\n", buffer);
}
if (!stopRequested) {
Sleep(5000); // 5秒后重试连接
}
}
}
// 守护线程函数
void __cdecl watchdogThread(void* arg) {
while (!stopRequested) {
if (!isConnected) {
printf("Watchdog: Connection is down, triggering reconnect...\n");
_beginthread(connectionThread, 0, NULL);
}
Sleep(10000); // 每10秒检查一次连接状态
}
}
int main() {
// 启动连接线程
_beginthread(connectionThread, 0, NULL);
// 启动守护线程
_beginthread(watchdogThread, 0, NULL);
// 主线程等待一段时间,模拟运行
Sleep(60000); // 等待60秒
// 关闭程序
stopRequested = 1;
closesocket(sock);
WSACleanup();
return 0;
}
新程序增加了 windows.h
和 process.h
来处理多线程。同时使用连接线程建立与服务器的连接,并且在连接丢失时重试。利用守护线程监控连接状态,如果连接断开,它将通知连接线程进行重新连接。最后在主函数中初始化 Winsock,并启动连接线程和守护线程。程序运行结果如图
输出结果显示多次连接,说明连接线程在守护线程触发时被多次启动。守护线程每 10 秒检查一次连接状态,如果发现未连接,会启动一个新的连接线程,但此时可能已经存在一个正在尝试连接的线程,这可能导致多个线程尝试使用同一个套接字。解决方法:限制守护线程的行为,守护线程启动新的连接线程之前,确保当前没有正在进行的连接尝试,可以使用额外的标志位来标识当前是否有正在尝试连接的线程。新程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <process.h> // _beginthread, _endthread
#pragma comment(lib, "ws2_32.lib")
#define HOST "cptest.axxc.cn"
#define PORT "30020"
// 全局变量,用于线程间通信
SOCKET sock = INVALID_SOCKET;
volatile int isConnected = 0;
volatile int stopRequested = 0;
volatile int connecting = 0; // 新增变量,用于标识是否正在尝试连接
// 连接线程函数
void __cdecl connectionThread(void* arg) {
struct addrinfo hints, * result, * ptr;
while (!stopRequested) {
WSADATA wsa;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed to initialize Winsock. Error Code: %d\n", WSAGetLastError());
return;
}
// 设置服务器地址信息
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(HOST, PORT, &hints, &result) != 0) {
printf("getaddrinfo failed: %d\n", WSAGetLastError());
WSACleanup();
return;
}
connecting = 1; // 开始连接前设置标志
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
if ((sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == INVALID_SOCKET) {
printf("Could not create socket: %d\n", WSAGetLastError());
WSACleanup();
return;
}
if (connect(sock, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR) {
closesocket(sock);
sock = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (sock == INVALID_SOCKET) {
printf("Unable to connect to server, retrying...\n");
WSACleanup();
Sleep(5000); // 5秒后重试
connecting = 0; // 连接失败,标志置为 0
continue;
}
printf("Connected to the server at %s:%s\n", HOST, PORT);
isConnected = 1;
connecting = 0; // 连接成功,标志置为 0
// 尝试发送消息到服务器
const char* message = "hello server!";
if (send(sock, message, strlen(message), 0) < 0) {
printf("send failed: %d\n", WSAGetLastError());
isConnected = 0; // 发送失败时关闭连接
}
else {
printf("message sent successfully.\n");
}
// 连接断开处理
while (isConnected && !stopRequested) {
char buffer[1024];
int bytes_received = recv(sock, buffer, sizeof(buffer) - 1, 0);
if (bytes_received == SOCKET_ERROR || bytes_received == 0) {
printf("Connection lost, attempting to reconnect...\n");
isConnected = 0;
closesocket(sock);
WSACleanup();
break;
}
buffer[bytes_received] = '\0';
printf("Received: %s\n", buffer);
}
if (!stopRequested) {
Sleep(5000); // 5秒后重试连接
}
}
}
// 守护线程函数
void __cdecl watchdogThread(void* arg) {
while (!stopRequested) {
if (!isConnected && !connecting) { // 确保没有正在尝试连接
printf("Watchdog: Connection is down, triggering reconnect...\n");
_beginthread(connectionThread, 0, NULL);
}
Sleep(10000); // 每10秒检查一次连接状态
}
}
int main() {
// 启动连接线程
_beginthread(connectionThread, 0, NULL);
// 启动守护线程
_beginthread(watchdogThread, 0, NULL);
// 主线程等待一段时间,模拟运行
Sleep(60000); // 等待60秒
// 关闭程序
stopRequested = 1;
closesocket(sock);
WSACleanup();
return 0;
}
该程序运行结果如下图
与
交替出现。说明即使已经加入了 connecting
标志,仍然存在多个连接线程被启动的情况。这可能是由于线程的非原子操作导致的竞态条件(gpt原话)。gpt建议加入线程互斥锁,以保证同时只有一个线程在运行。
======================================================================================================2024.08.31日更新===============================
加入互斥锁的程序如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <windows.h>
#include <process.h> // _beginthread, _endthread
#pragma comment(lib, "ws2_32.lib")
#define HOST "cptest.axxc.cn"
#define PORT "30020"
// 全局变量,用于线程间通信
SOCKET sock = INVALID_SOCKET;
volatile int isConnected = 0;
volatile int stopRequested = 0;
HANDLE connectionMutex; // 互斥锁
// 连接线程函数
void __cdecl connectionThread(void* arg) {
struct addrinfo hints, * result, * ptr;
while (!stopRequested) {
WaitForSingleObject(connectionMutex, INFINITE); // 获取互斥锁
WSADATA wsa;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
printf("Failed to initialize Winsock. Error Code: %d\n", WSAGetLastError());
ReleaseMutex(connectionMutex); // 释放互斥锁
return;
}
// 设置服务器地址信息
ZeroMemory(&hints, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
hints.ai_protocol = IPPROTO_TCP;
if (getaddrinfo(HOST, PORT, &hints, &result) != 0) {
printf("getaddrinfo failed: %d\n", WSAGetLastError());
WSACleanup();
ReleaseMutex(connectionMutex); // 释放互斥锁
return;
}
for (ptr = result; ptr != NULL; ptr = ptr->ai_next) {
if ((sock = socket(ptr->ai_family, ptr->ai_socktype, ptr->ai_protocol)) == INVALID_SOCKET) {
printf("Could not create socket: %d\n", WSAGetLastError());
WSACleanup();
ReleaseMutex(connectionMutex); // 释放互斥锁
return;
}
if (connect(sock, ptr->ai_addr, (int)ptr->ai_addrlen) == SOCKET_ERROR) {
closesocket(sock);
sock = INVALID_SOCKET;
continue;
}
break;
}
freeaddrinfo(result);
if (sock == INVALID_SOCKET) {
printf("Unable to connect to server, retrying...\n");
WSACleanup();
ReleaseMutex(connectionMutex); // 释放互斥锁
Sleep(5000); // 5秒后重试
continue;
}
printf("Connected to the server at %s:%s\n", HOST, PORT);
isConnected = 1;
ReleaseMutex(connectionMutex); // 释放互斥锁
// 尝试发送消息到服务器
const char* message = "hello server!";
if (send(sock, message, strlen(message), 0) < 0) {
printf("send failed: %d\n", WSAGetLastError());
isConnected = 0;
}
else {
printf("message sent successfully.\n");
}
// 连接断开处理
while (isConnected && !stopRequested) {
char buffer[1024];
int bytes_received = recv(sock, buffer, sizeof(buffer) - 1, 0);
if (bytes_received == SOCKET_ERROR || bytes_received == 0) {
printf("Connection lost, attempting to reconnect...\n");
isConnected = 0;
closesocket(sock);
WSACleanup();
break;
}
buffer[bytes_received] = '\0';
printf("Received: %s\n", buffer);
}
if (!stopRequested) {
Sleep(5000); // 5秒后重试连接
}
}
}
// 守护线程函数
void __cdecl watchdogThread(void* arg) {
while (!stopRequested) {
if (!isConnected) {
printf("Watchdog: Connection is down, triggering reconnect...\n");
_beginthread(connectionThread, 0, NULL);
}
Sleep(10000); // 每10秒检查一次连接状态
}
}
int main() {
// 创建互斥锁
connectionMutex = CreateMutex(NULL, FALSE, NULL);
// 启动连接线程
_beginthread(connectionThread, 0, NULL);
// 启动守护线程
_beginthread(watchdogThread, 0, NULL);
// 主线程等待一段时间,模拟运行
Sleep(60000); // 等待60秒
// 关闭程序
stopRequested = 1;
closesocket(sock);
WSACleanup();
// 释放互斥锁
CloseHandle(connectionMutex);
return 0;
}
程序运行结果如下图