windows C++创建个server端,地址为127.0.0.1 端口7799,接收client的信息并打印log
时间: 2024-09-21 07:03:17 浏览: 30
要在Windows上使用C++创建一个服务器端,可以使用Winsock库。以下是一个简单的示例,展示了如何创建一个服务器端,监听地址为127.0.0.1,端口为7799,接收客户端的信息并打印日志。
首先,确保已经安装了Winsock库。然后,创建一个新的C++项目,并在项目中包含以下头文件:
```cpp
#include <iostream>
#include <winsock2.h>
#pragma comment(lib, "ws2_32.lib")
```
接下来,编写以下代码:
```cpp
int main() {
WSADATA wsaData;
SOCKET ListenSocket, ClientSocket;
struct sockaddr_in server, client;
// 初始化Winsock
if (WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) {
std::cerr << "WSAStartup failed: " << WSAGetLastError() << std::endl;
return 1;
}
// 创建套接字
ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
std::cerr << "socket failed: " << WSAGetLastError() << std::endl;
WSACleanup();
return 1;
}
// 设置服务器地址和端口
server.sin_family = AF_INET;
server.sin_addr.s_addr = inet_addr("127.0.0.1");
server.sin_port = htons(7799);
// 绑定套接字
if (bind(ListenSocket, (struct sockaddr*)&server, sizeof(server)) == SOCKET_ERROR) {
std::cerr << "bind failed: " << WSAGetLastError() << std::endl;
closesocket(ListenSocket);
WSACleanup();
return 1;
}
// 监听连接
if (listen(ListenSocket, SOMAXCONN) == SOCKET_ERROR) {
std::cerr << "listen failed: " << WSAGetLastError() << std::endl;
closesocket(ListenSocket);
WSACleanup();
return 1;
}
std::cout << "Server is listening on 127.0.0.1:7799" << std::endl;
// 接受客户端连接
int clientSize = sizeof(client);
ClientSocket = accept(ListenSocket, (struct sockaddr*)&client, &clientSize);
if (ClientSocket == INVALID_SOCKET) {
std::cerr << "accept failed: " << WSAGetLastError() << std::endl;
closesocket(ListenSocket);
WSACleanup();
return 1;
}
std::cout << "Client connected" << std::endl;
// 接收并打印客户端信息
char buffer[1024];
int bytesReceived;
while ((bytesReceived = recv(ClientSocket, buffer, sizeof(buffer), 0)) > 0) {
buffer[bytesReceived] = '\0';
std::cout << "Received: " << buffer << std::endl;
}
// 关闭套接字
closesocket(ClientSocket);
closesocket(ListenSocket);
WSACleanup();
return 0;
}
```
编译并运行此代码,服务器将开始监听地址为127.0.0.1,端口为7799的连接。当客户端连接到服务器时,服务器将接收并打印客户端发送的信息。
阅读全文