win32控制台应用程序TCP服务器 向客户端发送数据三次代码
时间: 2024-11-03 17:16:03 浏览: 19
windows visual studio c++ tcp网络编程,包含服务端和客户端
在Windows环境下创建一个简单的TCP服务器,向连接的客户端发送三次数据,可以使用C++的Winsock库。以下是基本的代码示例:
```cpp
#include <winsock2.h>
#include <ws2tcpip.h>
#include <iostream>
#pragma comment(lib, "ws2_32.lib")
int main() {
WSADATA wsaData;
int iResult;
// 初始化 Winsock
iResult = WSAStartup(MAKEWORD(2, 2), &wsaData);
if (iResult != 0) {
std::cerr << "WSAStartup failed: " << WSAGetLastError() << std::endl;
return 1;
}
SOCKET ListenSocket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ListenSocket == INVALID_SOCKET) {
closesocket(ListenSocket);
WSACleanup();
std::cerr << "Could not create a listening socket" << std::endl;
return 1;
}
sockaddr_in ServerAddr;
ServerAddr.sin_family = AF_INET;
ServerAddr.sin_addr.S_un.S_addr = htonl(INADDR_ANY);
ServerAddr.sin_port = htons(8080); // 设置端口
// 绑定监听套接字到地址
if (bind(ListenSocket, (SOCKADDR*)&ServerAddr, sizeof(ServerAddr)) == SOCKET_ERROR) {
closesocket(ListenSocket);
WSACleanup();
std::cerr << "bind failed: " << WSAGetLastError() << std::endl;
return 1;
}
listen(ListenSocket, SOMAXCONN);
std::cout << "Listening for connections on port 8080..." << std::endl;
// 接收客户端连接并循环发送数据
char sendData[] = "Hello Client! This is the first message.\n";
while (true) {
SOCKET ClientSocket = accept(ListenSocket, NULL, NULL);
if (ClientSocket == INVALID_SOCKET) {
std::cerr << "accept failed: " << WSAGetLastError() << std::endl;
break;
}
iResult = send(ClientSocket, sendData, strlen(sendData), 0);
if (iResult > 0) {
std::cout << "Sent data to client." << std::endl;
} else if (iResult == 0) {
std::cerr << "send failed: " << WSAGetLastError() << std::endl;
} else {
std::cerr << "Error sending data: " << WSAGetLastError() << std::endl;
}
// 发送第二次和第三次数据
char sendData2[] = "This is the second message.\n";
iResult = send(ClientSocket, sendData2, strlen(sendData2), 0);
if (iResult > 0) {
std::cout << "Sent data to client." << std::endl;
}
char sendData3[] = "And this is the third message.\n";
iResult = send(ClientSocket, sendData3, strlen(sendData3), 0);
if (iResult > 0) {
std::cout << "Sent data to client." << std::endl;
}
closesocket(ClientSocket);
}
closesocket(ListenSocket);
WSACleanup();
return 0;
}
```
阅读全文