windows C++创建一个服务端类,ip为127.0.0.1 端口为7799,并分为.h和.cpp,并告诉我如何调用
时间: 2024-09-21 10:03:35 浏览: 32
在Windows上使用C++创建一个简单的TCP服务器,你需要定义一个服务端类,我们将这个类分别放在`ServerService.h`和`ServerService.cpp`文件中。首先,让我们定义`ServerService.h`:
```cpp
// ServerService.h
#pragma once
#include <winsock2.h>
#include <ws2tcpip.h>
#include <string>
class ServerService {
public:
ServerService();
~ServerService();
bool start(int port);
void stop();
private:
sockaddr_in server_addr;
SOCKET server_socket;
};
```
接下来,在`ServerService.cpp`中实现具体的函数:
```cpp
// ServerService.cpp
#include "ServerService.h"
ServerService::ServerService() {
// 初始化Winsock库
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Failed to initialize Winsock" << std::endl;
return;
}
}
ServerService::~ServerService() {
// 关闭并清理资源
closesocket(server_socket);
WSACleanup();
}
bool ServerService::start(int port) {
server_addr.sin_family = AF_INET; // IPv4
server_addr.sin_port = htons(port); // 将端口号转换成网络字节序
server_addr.sin_addr.s_addr = INADDR_ANY; // 0.0.0.0表示所有接口
if ((server_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) {
std::cerr << "Failed to create socket" << std::endl;
return false;
}
if (bind(server_socket, (SOCKADDR*)&server_addr, sizeof(server_addr)) != 0) {
std::cerr << "Failed to bind to address" << std::endl;
closesocket(server_socket);
return false;
}
if (listen(server_socket, SOMAXCONN) != 0) {
std::cerr << "Failed to listen on the socket" << std::endl;
closesocket(server_socket);
return false;
}
std::cout << "Server started on " << inet_ntoa(server_addr.sin_addr) << ":" << ntohs(server_addr.sin_port) << std::endl;
return true;
}
void ServerService::stop() {
shutdown(server_socket, SD_BOTH);
closesocket(server_socket);
}
```
要在其他地方调用这个服务,你可以这样做:
```cpp
int main() {
try {
ServerService service;
if (!service.start(7799)) {
throw std::runtime_error("Failed to start server");
}
// 等待服务停止(这里只是一个示例,实际应用需要添加适当的退出条件)
while (true) { sleep(1); }
service.stop();
} catch (const std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
```
在`main()`函数中,我们先初始化服务器,然后调用`start()`开始监听,接着进入一个无限循环等待,直到程序结束才调用`stop()`关闭服务器。
阅读全文