zoukankan      html  css  js  c++  java
  • 管道通信

    //服务端
    #include <stdio.h>
    #include <stdlib.h>
    #include <Windows.h>
    
    #define SIZE 4096//缓冲区大小
    char pipename[128] = "\\.\Pipe\cgwpipe";//管道名字
    HANDLE m_pipe = NULL;//管道句柄
    
    void start()
    {
      //创建管道 m_pipe
    = CreateNamedPipeA( pipename,//管道名称 PIPE_ACCESS_DUPLEX,//管道读写属性 PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,//消息模式,读模式,等待模式阻塞 PIPE_UNLIMITED_INSTANCES,//最大个数 SIZE,//输出缓冲区的大小 SIZE,//输入缓冲区的大小 0,//超时,无限等待 NULL);//安全属性 if (m_pipe == NULL) { printf("创建失败"); return; }
      //连接到管道,如果连接到这连接成功 连接不到看得到的错误是不是ERROR_PIPE_CONNECTED BOOL isconnect
    = ConnectNamedPipe(m_pipe, NULL) ? TRUE : (GetLastError() == ERROR_PIPE_CONNECTED); if (isconnect) { MessageBoxA(0, "connected", "提示", 0); } else { printf("链接失败 "); } MessageBoxA(0, "服务器启动", "提示", 0); }
    //读取
    void read() { char buf[SIZE] = { 0 }; int last = 0;//读取的个数 if (!ReadFile(m_pipe, buf, SIZE, &last, NULL)) { printf("服务器读取失败"); return; } printf(" read=%s", buf); } void write() { char str[128] = "锄禾日当午,管道真他么扯"; int last = 0; BOOL res = WriteFile(m_pipe, str, sizeof(str), &last, NULL); if (!res) { printf("写入失败"); return; } MessageBoxA(0, "服务器写入成功", "提示", 0); } void main() { start(); system("pause"); write(); system("pause"); read(); system("pause"); } //客户端 #include <stdio.h> #include <Windows.h> #define SIZE 4096 char pipename[128] = "\\.\Pipe\cgwpipe"; HANDLE m_pipe = NULL; void read() { char buf[SIZE] = { 0 }; int last = 0;//读取的个数 if (!ReadFile(m_pipe, buf, SIZE, &last, NULL)) { printf("客户端读取失败"); return; } printf(" read=%s", buf); } void write() { char str[128] = "客户端也这样认为"; int last = 0; BOOL res = WriteFile(m_pipe, str, sizeof(str), &last, NULL); if (!res) { printf("写入失败"); return; } MessageBoxA(0, "客户端写入成功", "提示", 0); } void main() {
      //看能否等到这个管道
    if (!WaitNamedPipeA(pipename, NMPWAIT_USE_DEFAULT_WAIT)) { MessageBoxA(0, " cannot connected", "提示", 0); return; }

      //CreateFileA 打开管道 m_pipe
    = CreateFileA(pipename, //名称 GENERIC_WRITE | GENERIC_READ,//权限 读写 1, //共享属性 NULL,//默认安全属性 OPEN_EXISTING,//从已经存在的寻找 FILE_ATTRIBUTE_NORMAL, //默认已经存在的属性 NULL); system("pause"); read(); system("pause"); write(); system("pause"); }
  • 相关阅读:
    网页加速的14条优化法则 网站开发与优化
    .NET在后置代码中输入JS提示语句(背景不会变白)
    C语言变量声明内存分配
    SQL Server Hosting Toolkit
    An established connection was aborted by the software in your host machine
    C语言程序设计 2009春季考试时间和地点
    C语言程序设计 函数递归调用示例
    让.Net 程序脱离.net framework框架运行
    C语言程序设计 答疑安排(2009春季 110周) 有变动
    软件测试技术,软件项目管理 实验时间安排 2009春季
  • 原文地址:https://www.cnblogs.com/xiaochi/p/5677195.html
Copyright © 2011-2022 走看看