【发布时间】:2016-06-14 20:26:36
【问题描述】:
我正在尝试使用命名管道将 c# 项目与 c++ 项目连接,但 c++ 项目未连接。
ps: .exe 都在同一个文件中
附带问题:我不明白在我的管道名称前使用“\\.\pipe\”。它有什么作用,真的有必要吗?
这是我的代码,也许你能发现错误
C# 服务器:
程序.cs
static class Program
{
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
pipeHandler pipe = new pipeHandler();
var proc = new Process();
proc.StartInfo.FileName = "cplpltestpipes.exe";
proc.Start();
pipe.establishConnection();
Application.Run(new Form1(pipe));
}
}
public class pipeHandler
{
private StreamReader re;
private StreamWriter wr;
private NamedPipeServerStream pipeServer;
public void establishConnection()
{
pipeServer = new NamedPipeServerStream("myNamedPipe1");
pipeServer.WaitForConnection();
re = new StreamReader(pipeServer);
wr = new StreamWriter(pipeServer);
}
public void writePipe(string text)
{
wr.Write(text);
}
public string readPipe()
{
if(re.Peek()==-1)
System.Threading.Thread.Sleep(2000);
if (re.Peek() > -1)
{
string s;
s = re.ReadToEnd();
return s;
}
else
return "fail";
}
}
Form1.cs:
public partial class Form1 : Form
{
pipeHandler pipePointer;
public Form1(pipeHandler pipe)
{
pipePointer=pipe;
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
pipePointer.writePipe(textBox1.Text);
textBox2.Text = pipePointer.readPipe();
}
}
c++ 客户端
#define chrSize 16
int main()
{
TCHAR chr[chrSize];
DWORD bytesRead;
HANDLE pipeHandler;
LPTSTR pipeName = TEXT("\\\\.\\pipe\\myNamedPipe1");
pipeHandler = CreateFile(
pipeName, // pipe name
GENERIC_READ | // read and write access
GENERIC_WRITE,
0, // no sharing
NULL, // default security attributes
OPEN_EXISTING, // opens existing pipe
0, // default attributes
NULL); // no template file
bool flag=false;
while (!flag)
{
flag = ConnectNamedPipe(pipeHandler, NULL);
cout << "trying";
}
ReadFile(
pipeHandler, // pipe handle
chr, // buffer to receive reply
chrSize * sizeof(TCHAR), // size of buffer
&bytesRead, // number of bytes read
NULL); // not overlapped
cout << chr;
LPTSTR pipeMessage = TEXT("message receive");
DWORD bytesToWrite= (lstrlen(pipeMessage) + 1) * sizeof(TCHAR);
DWORD cbWritten;
WriteFile(
pipeHandler, // pipe handle
pipeMessage, // message
bytesToWrite, // message length
&cbWritten, // bytes written
NULL); // not overlapped
CloseHandle(pipeHandler);
}
运行程序只会在 C# 中给出这个异常
**************异常文本************** System.InvalidOperationException:管道尚未连接。 …… …… ....
而在 c++ 中,只是在控制台中不断打印“正在尝试”
【问题讨论】:
-
我在你的代码中没有看到
"\\.\pipe\。 -
它不存在,因为我现在不知道它的作用,它也不管用
-
请参阅msdn.microsoft.com/en-us/library/windows/desktop/… 了解管道名称的说明。
-
这就是我获得代码的方式。但我不明白为什么它不连接
标签: c# c++ named-pipes