异步套接字示例

时间:2018-02-16 16:54:21

标签: c# sockets

我正在学习使用C#的套接字,我从以下链接实现了客户端和服务器示例:

服务器 - https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-server-socket-example

客户 - https://docs.microsoft.com/en-us/dotnet/framework/network-programming/asynchronous-client-socket-example

如果我运行一次,示例工作就没问题了。所以,我尝试修改我可以运行客户端多次一次的示例。这是我做的改变。

public static int Main(String[] args)
{
    string msg = string.Empty;
    while (msg != "exit")
    {
        Console.WriteLine("Enter a message:");
        msg = Console.ReadLine();

        if (msg != "exit")
            StartClient(msg);
    }

    return 0;
}

问题是当我将第二条消息发送到服务器时,它会在命令int bytesRead = client.EndReceive(ar);上抛出'System.ObjectDisposedException'

private static void ReceiveCallback(IAsyncResult ar)
{
    try
    {
        // Retrieve the state object and the client socket   
        // from the asynchronous state object.  
        StateObject state = (StateObject)ar.AsyncState;
        Socket client = state.workSocket;

        // Read data from the remote device.  
        int bytesRead = client.EndReceive(ar); // This line throws an exception.

        if (bytesRead > 0)
        {
            //...
        }
        //...
    }
}

有谁能告诉我我做错了什么?

我对服务器套接字也有疑问。在示例中,我需要使用<EOF>结束消息。如何修改服务器以读取所有字节(我不知道大小)而不必使用<EOF>完成我的消息?

感谢所有人!

0 个答案:

没有答案