简单的Mailslot程序无法正常工作?

时间:2010-03-14 20:42:42

标签: windows visual-studio-2008 writefile mailslot

使用此处的客户端和服务器示例:http://www.winsocketdotnetworkprogramming.com/winsock2programming/winsock2advancedmailslot14.html使用VS2008编译它们,运行服务器然后“客户端Myslot”我不断收到“WriteFail失败,错误53”。有人有主意吗?还欢迎链接到其他Mailslot示例,谢谢。

服务器:

    // Server sample
#include <windows.h>
#include <stdio.h>

void main(void)
{

    HANDLE Mailslot;
    char buffer[256];
    DWORD NumberOfBytesRead;

    // Create the mailslot

    if ((Mailslot = CreateMailslot("\\\\.\\Mailslot\\Myslot", 0, MAILSLOT_WAIT_FOREVER, NULL)) == INVALID_HANDLE_VALUE)
    {
        printf("Failed to create a mailslot %d\n", GetLastError());
        return;
    } 

    // Read data from the mailslot forever!

    while(ReadFile(Mailslot, buffer, 256, &NumberOfBytesRead, NULL) != 0)
    {
        printf("%.*s\n", NumberOfBytesRead, buffer);
    }
}

客户端:

// Client sample

#include <windows.h>
#include <stdio.h>

void main(int argc, char *argv[])
{
    HANDLE Mailslot;
    DWORD BytesWritten;
    CHAR ServerName[256];

    // Accept a command line argument for the server to send a message to

    if (argc < 2)
    {
        printf("Usage: client <server name>\n");
        return;
    }

    sprintf(ServerName, "\\\\%s\\Mailslot\\Myslot", argv[1]);

    if ((Mailslot = CreateFile(ServerName, GENERIC_WRITE,

        FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL)) == INVALID_HANDLE_VALUE)
    {
        printf("CreateFile failed with error %d\n", GetLastError());
        return;
    }

    if (WriteFile(Mailslot, "This is a test", 14, &BytesWritten, NULL) == 0)
    {
        printf("WriteFile failed with error %d\n", GetLastError());
        return;
    }

    printf("Wrote %d bytes\n", BytesWritten);
    CloseHandle(Mailslot);
}

2 个答案:

答案 0 :(得分:1)

错误53是ERROR_BAD_NETPATH,“找不到网络路径”。显然,您使用错误的服务器名称作为邮件槽。如果服务器与客户端在同一台计算机上运行,​​请使用\\.\mailslot\blah。并且不要忘记转义字符串中的反斜杠:"\\\\.\\mailslot\\blah"

答案 1 :(得分:1)

我将完全复制的代码复制到两个文件中,用VS2008编译它们并且运行完美。如果您的客户端程序编译为client.exe,则键入以下命令:

client .

client <computername>

其中计算机名称是没有域名的PC名称。您可以调用API GetComputerName来检索名称。