我对 Windows (C/C++) 中的 MailSlots 有疑问。
我现在正在尝试制作两个简单的程序,但是最后一步的沟通并不好。
这是我来自 server.cpp 的 int main
int main()
{
HANDLE ss, sc, sc2r;
LPCTSTR errMsg;
ss = CreateMailslot("\\\\.\\mailslot\\ss", 0, MAILSLOT_WAIT_FOREVER, NULL);
if (ss == INVALID_HANDLE_VALUE)
{
printf("Invalid ss value");
return -1;
}
for (;;)
{
DWORD msgSize;
DWORD nr;
BOOL err;
/* Get the size of the next record */
err = GetMailslotInfo(ss, 0, &msgSize, 0, 0);
char x[100];
char nrr[10];
if (msgSize != (DWORD)MAILSLOT_NO_MESSAGE)
{
DWORD numRead;
/* Read the record */
err = ReadFile(ss, x, msgSize, &numRead, 0);
int wrds=count(x)+1;
sc = CreateFile("\\\\*\\mailslot\\sc", GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
itoa(wrds,nrr,10);
err = WriteFile(sc, nrr, sizeof(nrr), &nr, 0);
//cout<<err<<endl;
//cout<<x;
//cout<<err;
strrev(x);
err=WriteFile(sc, x, sizeof(x), &nr, 0);
}
}
return(0);
}
这是客户端来源:
int main()
{
HANDLE ss, sc, sc2;
LPCTSTR errMsg;
BOOL err;
DWORD numWritten;
sc = CreateMailslot("\\\\.\\mailslot\\sc", 0, MAILSLOT_WAIT_FOREVER, NULL);
ss = CreateFile("\\\\*\\mailslot\\ss", GENERIC_WRITE, FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
if (ss == INVALID_HANDLE_VALUE)
{
printf("CreateFile failed. ");
// Close any mailslot we opened
if (ss != INVALID_HANDLE_VALUE) CloseHandle(ss);
return -1;
}
char x[100];
char z[100];
printf("Write the damn sentence:");
cin.getline(x,100);
err = WriteFile(ss, x, sizeof(x), &numWritten, 0);
if (!err) printf("WriteFile failed. ");
DWORD rd;
ReadFile(sc,x,sizeof(x),&rd,NULL);
cout<<x<<endl;
ReadFile(sc,z,sizeof(z),&rd,NULL);
cout<<z;
return 0;
}
似乎服务器正在发送三遍相同的东西。我在调试器中测试了客户端,他做对了,但无法弄清楚为什么服务器会发送三倍相同的东西。
你有什么建议吗 ?