下面是一个简单的示例代码,演示了在Windows下使用C++实现TCP的P2P模式:
服务器端代码:
#include <iostream>
#include <winsock2.h>
#define PORT 8080
int main() {
WSADATA wsaData;
SOCKET serverSocket, clientSocket;
SOCKADDR_IN serverAddr, clientAddr;
// 初始化Winsock库
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cout << "Failed to initialize Winsock" << std::endl;
return -1;
}
// 创建服务器端socket
serverSocket = socket(AF_INET, SOCK_STREAM, 0);
if (serverSocket == INVALID_SOCKET) {
std::cout << "Failed to create socket" << std::endl;
WSACleanup();
return -1;
}
// 设置服务器地址和端口
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_addr.s_addr = INADDR_ANY;
serverAddr.sin_port = htons(PORT);
// 绑定socket到指定地址和端口
if (bind(serverSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cout << "Failed to bind socket" << std::endl;
closesocket(serverSocket);
WSACleanup();
return -1;
}
// 监听连接请求
if (listen(serverSocket, SOMAXCONN) == SOCKET_ERROR) {
std::cout << "Listen failed with error" << std::endl;
closesocket(serverSocket);
WSACleanup();
return -1;
}
// 等待客户端连接
std::cout << "Server listening on port " << PORT << std::endl;
int clientAddrSize = sizeof(clientAddr);
clientSocket = accept(serverSocket, (struct sockaddr*)&clientAddr, &clientAddrSize);
if (clientSocket == INVALID_SOCKET) {
std::cout << "Accept failed with error" << std::endl;
closesocket(serverSocket);
WSACleanup();
return -1;
}
// 和客户端进行通信...
// 关闭socket和清理Winsock库
closesocket(clientSocket);
closesocket(serverSocket);
WSACleanup();
return 0;
}
客户端代码:
#include <iostream>
#include <winsock2.h>
#define SERVER_IP "127.0.0.1"
#define PORT 8080
int main() {
WSADATA wsaData;
SOCKET clientSocket;
SOCKADDR_IN serverAddr;
// 初始化Winsock库
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cout << "Failed to initialize Winsock" << std::endl;
return -1;
}
// 创建客户端socket
clientSocket = socket(AF_INET, SOCK_STREAM, 0);
if (clientSocket == INVALID_SOCKET) {
std::cout << "Failed to create socket" << std::endl;
WSACleanup();
return -1;
}
// 设置服务器地址和端口
memset(&serverAddr, 0, sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
if (inet_pton(AF_INET, SERVER_IP, &(serverAddr.sin_addr)) <= 0) {
std::cout << "Invalid address/Address not supported" << std::endl;
closesocket(clientSocket);
WSACleanup();
return -1;
}
// 连接到服务器
if (connect(clientSocket, (struct sockaddr*)&serverAddr, sizeof(serverAddr)) == SOCKET_ERROR) {
std::cout << "Failed to connect to server" << std::endl;
closesocket(clientSocket);
WSACleanup();
return -1;
}
// 和服务器进行通信...
// 关闭socket和清理Winsock库
closesocket(clientSocket);
WSACleanup();
return 0;
}
这只是一个简单的示例,仅涉及了连接的建立,并未实现P2P通信。要实现完整的P2P通信,需要在客户端之间建立直接连接,可以使用STUN、TURN或其他技术来解决NAT穿透问题。
请注意,上述代码仅适用于Windows环境,并且省略了错误处理和一些安全性和稳定性的考虑。在实际开发中,需要进行更多细节的处理和优化。
内容由零声教学AI助手提供,问题来源于学员提问