#include <Windows.h> #include <iostream> using namespace std; int main() { HANDLE hPipe; char buffer[1024] = "Hello from client!"; DWORD dwBytesWritten; //连接命名管道 hPipe = CreateFile(TEXT("\\\\.\\pipe\\MyPipe"), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hPipe == INVALID_HANDLE_VALUE) { cout << "Failed to connect to server!" << endl; return 1; } //发送数据 if (WriteFile(hPipe, buffer, strlen(buffer), &dwBytesWritten, NULL)) { cout << "Message sent!" << endl; } else { cout << "Failed to send message!" << endl; } //关闭命名管道 CloseHandle(hPipe); return 0; }改进代码
时间: 2023-06-17 21:05:04 浏览: 330
#include_iostream.h_
4星 · 用户满意度95%
改进代码如下:
#include <Windows.h>
#include <iostream>
using namespace std;
int main() {
HANDLE hPipe;
char buffer[1024] = "Hello from client!";
DWORD dwBytesWritten;
// 连接命名管道
hPipe = CreateFile(TEXT("\\\\.\\pipe\\MyPipe"), GENERIC_WRITE, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hPipe == INVALID_HANDLE_VALUE) {
cout << "Failed to connect to server!" << endl;
return 1;
}
// 发送数据
if (WriteFile(hPipe, buffer, strlen(buffer), &dwBytesWritten, NULL)) {
cout << "Message sent!" << endl;
}
else {
cout << "Failed to send message!" << endl;
}
// 关闭命名管道
CloseHandle(hPipe);
return 0;
}
这份代码是一个简单的命名管道客户端程序,通过连接到服务器端的命名管道,向服务器端发送一条消息。这份代码的改进点在于加入了注释,使代码更易读懂。
阅读全文