windows C++创建一个服务端类,ip为127.0.0.1 端口为7799,并分为.h和.cpp,并告诉我如何调用,我要全部完整的代码
时间: 2024-09-20 13:14:01 浏览: 45
在Windows上创建一个C++的服务端程序,通常会使用`WSAStartup`和`WSACleanup`初始化和清理Winsock库,以及`SOCKET`, `bind()`, `listen()`和`accept()`等网络函数来监听连接。下面是一个简单的例子,我们将创建一个名为`ServerService`的类,包含`.h`和`.cpp`两个文件。
**ServerService.h**
```cpp
#pragma once
#include <winsock2.h>
#include <ws2tcpip.h>
class ServerService {
public:
ServerService();
~ServerService();
bool start(int port);
void stop();
private:
SOCKET serverSocket;
sockaddr_in serverAddress;
};
```
**ServerService.cpp**
```cpp
#include "ServerService.h"
ServerService::ServerService() {
WSADATA wsaData;
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "Error initializing Winsock." << std::endl;
return;
}
}
ServerService::~ServerService() {
closesocket(serverSocket);
WSACleanup();
}
bool ServerService::start(int port) {
serverSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket == INVALID_SOCKET) {
std::cerr << "Failed to create socket." << std::endl;
return false;
}
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); // Listen on all interfaces
serverAddress.sin_port = htons(port);
if (bind(serverSocket, (sockaddr*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) {
std::cerr << "Failed to bind socket." << std::endl;
closesocket(serverSocket);
return false;
}
listen(serverSocket, SOMAXCONN); // Max connections
std::cout << "Server started on port " << port << "." << std::endl;
return true;
}
void ServerService::stop() {
closesocket(serverSocket);
}
```
为了调用这个服务,你需要在主程序中实例化`ServerService`并启动它:
```cpp
int main() {
ServerService service;
if (!service.start(7799)) {
return -1;
}
try {
// Wait for user to press a key or until the service is stopped manually
MSG msg;
while (GetMessage(&msg, nullptr, 0, 0)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
} catch (...) {
service.stop();
}
return 0;
}
```
在上述代码中,`main`函数会一直等待用户交互,直到停止服务。你可以通过关闭程序窗口来触发`stop()`函数。
阅读全文