Client code:
#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <ctime> int main (int argc, _t char* argv[]) {Srand (Time (NULL)); DWORD Wlen = 0; Sleep (1000);//wait for the pipe to be created successfully! BOOL BRet = Waitnamedpipe (TEXT ("\\\\.\\pipe\\mypipe"), nmpwait_wait_forever); if (!bret) {printf ("Connect the Namedpipe failed!\n"); return 0; } HANDLE hpipe = CreateFile (//pipe belongs to a special file TEXT ("\\\\.\\pipe\\mypipe"),//filename created by GENE Ric_read | Generic_write,//File mode 0,//whether to share NULL,//point to an SEC Urity_attributes structure of the pointer open_existing,//create parameter File_attribute_normal,//File attributes (hidden, only Read) Normal is the default property NULL); The template creates a handle to the file if (Invalid_handle_value = = hpipe) {printf ("Open the Exit pipe failed!\n"); } else {while (true){char buf[256] = ""; sprintf (buf, "%s%d", Buf,rand ()%1000); if (WriteFile (hpipe,buf,sizeof (BUF), &wlen,0) ==false)//send content to server {printf ("Write to Pipe F Ailed!\n "); Break } else {printf ("to Server:data =%s, size =%d\n", buf, Wlen); Char rbuf[256] = ""; DWORD Rlen = 0; ReadFile (hpipe, Rbuf, sizeof (RBUF), &rlen, 0); Accept the service sent over the contents of printf ("from server:data =%s, size =%d\n", Rbuf, Rlen); } Sleep (1000); } closehandle (hpipe);//Close Pipe} system ("Pause"); return 0; }
Service-Side code:
#include "stdafx.h" #include <stdio.h> #include <windows.h> #include <ctime> int main (int argc, _t char* argv[]) {Srand (Time (NULL)); Char buf[256] = ""; DWORD Rlen = 0; HANDLE hpipe = CreateNamedPipe (TEXT ("\\\\.\\pipe\\mypipe"),//pipe name Pipe_access_du PLEX,//pipe type pipe_type_message| pipe_readmode_message| Pipe_wait,//Pipe parameters Pipe_unlimited_instances,//pipeline can create maximum number of instances 0, Output buffer length 0 means default 0,//input buffer length 0 Represents the default Nmpwait_wait_forever,//timeout time NULL); Specify a security_attributes structure, or pass a 0 value if (invalid_handle_value = = hpipe) {printf ("Create P Ipe Error (%d) \ n ", GetLastError ()); } else {printf ("Waiting for Client connection...\n "); if (! Connectnamedpipe (Hpipe, NULL))//blocking waits for client connections. {printf ("Connection failed!\n"); } else {printf ("Connection success!\n"); } while (true) {if (! ReadFile (Hpipe,buf,256,&rlen,null))//Accept the content sent by the client {printf ("Read Data from P Ipe failed!\n "); Break } else {printf ("from client:data =%s, size =%d\n", buf, Rlen); Char wbuf[256] = ""; sprintf (WBUF, "%s%d", Wbuf, Rand ()%1000); DWORD Wlen = 0; WriteFile (hpipe, wbuf, sizeof (WBUF), &wlen, 0); Send content to client printf ("To Client:data =%s, size =%d\n", wbuf, Wlen); Sleep (1000); }} flushfilebuffers (Hpipe); DisconnectnamedpipE (hpipe); CloseHandle (hpipe);//Close Pipe} system ("Pause"); return 0; }