c++/c#命名管道通信问题,服务端能读,不能写。

代码太长了,换个帐号贴在下面。... 代码太长了,换个帐号贴在下面。 展开
 我来答
匿名用户
推荐于2016-11-15
展开全部
// 
服务器可以接收客户端消息,但是不能发送消息,write函数一直阻塞,换用sw.write仍然一样的。 
//服务器端:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.IO.Pipes;
using System.Threading;
namespace FrmServer
{
    public partial class FrmServer : Form
    {
        
        public delegate void SetTextDelegate(string text);
         NamedPipeServerStream pipeServer; 
         StreamWriter sw;
         StreamReader sr;
        public FrmServer()
        {
            InitializeComponent();
            //process1.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
            //process1.StartInfo.FileName = "MiniFetion";
            //process1.Start();
            Thread th = new Thread(new ThreadStart(CreateNamedPipe));
            th.Start();
           
        }
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                textBox1.Text = "PipeServer Message";
                byte[] buffer = Encoding.UTF8.GetBytes(textBox1.Text);
                pipeServer.Write(buffer,0,buffer.Length);
                label1.Invoke(new SetTextDelegate(SetTextDo), buffer);
            }
            catch (IOException ex)
            {
                label1.Text = ex.Message;
            }
        }
        private void CreateNamedPipe()
        {
            pipeServer = new NamedPipeServerStream("FetionPipe", PipeDirection.InOut, 1, PipeTransmissionMode.Byte);
            pipeServer.WaitForConnection();
            sw = new StreamWriter(pipeServer);
            sr = new StreamReader(pipeServer);
            sw.AutoFlush = true;
            if (pipeServer.IsConnected) 
            {
                label1.Invoke(new SetTextDelegate(SetTextDo), "管道客户端已连接");
            }
            //sw.Write("login",new UTF8Encoding(false));
            if (label1.InvokeRequired)
            {
                label1.Invoke(new SetTextDelegate(SetTextDo), "管道客户端已连接");
            }
            //监听管道
            while(true)
            {
                // Process the incoming message.
                //GetAnswerToRequest(pchRequest, pchReply, &cbReplyBytes);
                try
                {
                    if (label1.InvokeRequired)
                    {
                        byte[] buffer = new byte[255];
                        pipeServer.Read(buffer, 0, 255);
                        label1.Invoke(new SetTextDelegate(SetTextDo), Encoding.UTF8.GetString(buffer));
                        Thread.Sleep(100);
                    }
                    //处理消息
                    
                }
                catch(IOException ex)
                {
                    if (label1.InvokeRequired)
                    {
                        label1.Invoke(new SetTextDelegate(SetTextDo),ex.Message);
                    }
                }

            }
        }
        public void SetTextDo(string text) { label1.Text = text; }
    }
}

//客户端

#include "stdafx.h"
#include "FetionPipe.h"

HANDLE CFetionPipe::hPipeClient = NULL;//初始化静态成员变量
HANDLE CFetionPipe::CreateClient()
{
 CString lpPipeName="\\\\.\\pipe\\FetionPipe";
 LPTSTR lpszPipename = new TCHAR[lpPipeName.GetLength()+1];
 _tcscpy(lpszPipename, lpPipeName);
 /*if (WaitNamedPipe(lpszPipename, 5000)==false)
 {
  return NULL;
 }*/
 hPipeClient = CreateFile(
                 lpszPipename,
                 GENERIC_WRITE|GENERIC_READ,
                 0,
                 NULL, 
                 OPEN_EXISTING,
                 0,
                 NULL);
 while(true)
 {
  if(hPipeClient == INVALID_HANDLE_VALUE)
  {
   CString strLastError;
   strLastError.Format("%d",GetLastError());
   AfxMessageBox("Error open pipes, the Last Error number is:"+strLastError);
   Sleep(5000);
   hPipeClient = CreateFile(
     lpszPipename,
                 GENERIC_WRITE|GENERIC_READ,
                 0,
                 NULL, 
                 OPEN_EXISTING,
                 0,
                 NULL);
  }
  else
  {
   AfxMessageBox("Success open pipes");
   break;
  }
 }
  //设置管道状态 
 DWORD dwMode = PIPE_READMODE_BYTE; 
 BOOL fSuccess = SetNamedPipeHandleState( 
         hPipeClient,       // pipe handle 
         &dwMode,          // new pipe mode 
         NULL,             // don't set maximum bytes 
         NULL);            // don't set maximum time 
 if ( ! fSuccess) 
 {
  AfxMessageBox("Failed SetNamedPipeHandleState");
 }
 return hPipeClient;
}
DWORD WINAPI CFetionPipe::Listenner(LPVOID lpParameter)
 {
  //创建文件
  hPipeClient = CreateClient();//hPipeClient静态变量
  DWORD dwRead,dwWritten;
  TCHAR* Msg; 
  BOOL   fSuccess = FALSE; 
  DWORD cbRead, cbToWrite, cbWritten, dwMode;
  LPTSTR lpvMessage=TEXT("Msg:FetionPipe Success!");
  fSuccess = MsgWrite(lpvMessage);
  
  while(hPipeClient != INVALID_HANDLE_VALUE)
  {
   Msg = MsgRead();
   if(Msg!=NULL)
   {
    AfxMessageBox(Msg);
    MsgHandle(Msg);
   }
   
   }
   return 0;
 }

BOOL CFetionPipe::MsgHandle(TCHAR* pszMsg)
{
 pszMsg = TEXT("Received Message!");
 MsgWrite(pszMsg);
 return 0;
}
BOOL CFetionPipe::MsgWrite(TCHAR* pszMsg)//写管道消息
{
 BOOL   fSuccess = FALSE; 
 DWORD cbToWrite, cbWritten;
 LPTSTR lpvMessage = TEXT(pszMsg);
 cbToWrite = (lstrlen(lpvMessage)+1)*sizeof(TCHAR);        
 fSuccess = WriteFile( 
                 hPipeClient,            // pipe handle 
                 lpvMessage,             // message 
                 cbToWrite,              // message length 
                 &cbWritten,             // bytes written 
                 NULL);
   return fSuccess;
}
TCHAR* CFetionPipe::MsgRead()//读管道消息
{
 DWORD dwRead,dwWritten;
 TCHAR* chBuf = NULL; 
 BOOL   fSuccess = FALSE; 
 DWORD cbRead, cbToWrite, cbWritten, dwMode;
 do 
         { 
                 // Read from the pipe.                 
                 fSuccess = ReadFile( 
                         hPipeClient,     // pipe handle 
                         chBuf,           // buffer to receive reply 
                         BUFSIZ*sizeof(TCHAR),   // size of buffer 
                         &cbRead,         // number of bytes read 
                         NULL);           // not overlapped 
                 
                 if ( ! fSuccess && GetLastError() != ERROR_MORE_DATA )
                 {
                         break; 
                 }
     Sleep(100);
 
         } while (!fSuccess);  // repeat loop if ERROR_MORE_DATA
   return chBuf;
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式