windows C++创建一个服务端类,ip为127.0.0.1 端口为7799,并分为.h和.cpp,
时间: 2024-09-20 11:13:04 浏览: 62
首先,我们需要创建一个服务端类,该类包含IP地址和端口号。接下来,我们将在头文件(.h)中声明类的成员变量和方法,然后在源文件(.cpp)中实现这些方法。
1. 创建一个名为"Server.h"的头文件:
```cpp
#pragma once
#include <iostream>
#include <string>
#include <WS2tcpip.h>
#include <winsock2.h>
class Server {
public:
Server(const std::string& ip, int port);
~Server();
bool start();
void stop();
private:
std::string ip_;
int port_;
SOCKET serverSocket_;
};
```
2. 创建一个名为"Server.cpp"的源文件:
```cpp
#include "Server.h"
Server::Server(const std::string& ip, int port) : ip_(ip), port_(port) {
WSADATA wsaData;
int result = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (result != 0) {
std::cerr << "WSAStartup failed with error: " << result << std::endl;
exit(1);
}
}
Server::~Server() {
WSACleanup();
}
bool Server::start() {
serverSocket_ = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (serverSocket_ == INVALID_SOCKET) {
std::cerr << "Error creating socket: " << WSAGetLastError() << std::endl;
return false;
}
sockaddr_in serverAddress;
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = inet_addr(ip_.c_str());
serverAddress.sin_port = htons(port_);
if (bind(serverSocket_, (SOCKADDR*)&serverAddress, sizeof(serverAddress)) == SOCKET_ERROR) {
std::cerr << "Bind failed with error: " << WSAGetLastError() << std::endl;
closesocket(serverSocket_);
return false;
}
if (listen(serverSocket_, SOMAXCONN) == SOCKET_ERROR) {
std::cerr << "Listen failed with error: " << WSAGetLastError() << std::endl;
closesocket(serverSocket_);
return false;
}
return true;
}
void Server::stop() {
closesocket(serverSocket_);
}
```
现在,你可以在你的主程序中使用这个Server类来创建一个服务端实例并启动它。例如:
```cpp
#include "Server.h"
int main() {
Server server("127.0.0.1", 7799);
if (server.start()) {
std::cout << "Server started successfully." << std::endl;
// Do something with the server...
} else {
std::cerr << "Failed to start the server." << std::endl;
}
// When you're done with the server, stop it
server.stop();
return 0;
}
```
阅读全文