套接字读取冻结

时间:2015-05-08 18:20:33

标签: c# sockets

我正在开展小型课程以便学习。

我的程序是简单的Telnet控制台。

使用visual studio 2010 Express我现在创建了非常酷的用户界面我尝试与远程服务器(Creston控制处理器)建立通信。我从this Microsoft article复制并粘贴了课程,当我执行课程时,程序会冻结。我不确定如何正确描述会发生什么,但在基本单词中所有控件(包括关闭按钮)都停止工作。

这是我班级的代码:(我添加了一些调试行);

public class StateObject
{
    // Client socket.
    public Socket workSocket = null;
    // Size of receive buffer.
    public const int BufferSize = 256;
    // Receive buffer.
    public byte[] buffer = new byte[BufferSize];
    // Received data string.
    public StringBuilder sb = new StringBuilder();
    public string TempString = string.Empty;
    public int TotalBytesRead = 0;
    public char[] charBuffer = new char[1000];
}
public class AsynchronousClient
{
    // The port number for the remote device.
    private const int port = 23;

    // ManualResetEvent instances signal completion.
    private static ManualResetEvent connectDone =
        new ManualResetEvent(false);
    private static ManualResetEvent sendDone =
        new ManualResetEvent(false);
    private static ManualResetEvent receiveDone =
        new ManualResetEvent(false);

    // The response from the remote device.
    private static String response = String.Empty;
    public AsynchronousClient()
    {

    }
    public void New()
    {
        StartClient();
    }
    private static void StartClient()
    {
        // Connect to a remote device.
        try
        {
            // Establish the remote endpoint for the socket.
            // The name of the 
            // remote device is "host.contoso.com".
            IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse("10.106.6.60"), port);

            // Create a TCP/IP socket.
            Socket client = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream, ProtocolType.Tcp);

            // Connect to the remote endpoint.
            client.BeginConnect(remoteEP,
                new AsyncCallback(ConnectCallback), client);
            connectDone.WaitOne();
            Console.WriteLine("StartSend");
            // Send test data to the remote device.
            //Send(client, "hostname\n");
            //sendDone.WaitOne();
            Console.WriteLine("WaitForResponse");
            // Receive the response from the remote device.
            Receive(client);
            receiveDone.WaitOne();

            // Write the response to the console.
            Console.WriteLine("Read From Socket : {0}", response);
            Console.WriteLine("ReleaseSocket");
            // Release the socket.
            client.Shutdown(SocketShutdown.Both);
            client.Disconnect(true);

        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void ConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete the connection.
            client.EndConnect(ar);

            Console.WriteLine("Socket connected to {0}",
                client.RemoteEndPoint.ToString());

            // Signal that the connection has been made.
            connectDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void Receive(Socket client)
    {
        try
        {
            // Create the state object.
            Console.WriteLine("Receive");
            StateObject state = new StateObject();
            state.workSocket = client;

            // Begin receiving the data from the remote device.
            client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

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

            // Read data from the remote device.
            int bytesRead = client.EndReceive(ar);
            Console.WriteLine("Bytes read: {0}", bytesRead);
            if (bytesRead > 0)
            {
                // There might be more data, so store the data received so far.
                string tsTempString = Encoding.ASCII.GetString(state.buffer, 0, bytesRead);
                state.TempString += tsTempString;
                Console.WriteLine("String {0}",  tsTempString);
                state.sb.Append(Encoding.ASCII.GetString(state.buffer, 0, bytesRead));

                // Get the rest of the data.
                client.BeginReceive(state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state);
            }
            else
            {
                // All the data has arrived; put it in response.
                if (state.sb.Length > 1)
                {
                    response = state.sb.ToString();
                }
                // Signal that all bytes have been received.
                receiveDone.Set();
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

    private static void Send(Socket client, String data)
    {
        Console.WriteLine("Send");
        // Convert the string data to byte data using ASCII encoding.
        byte[] byteData = Encoding.ASCII.GetBytes(data);

        // Begin sending the data to the remote device.
        client.BeginSend(byteData, 0, byteData.Length, 0,
            new AsyncCallback(SendCallback), client);
    }

    private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            Console.WriteLine("SendCallBack");
            // Retrieve the socket from the state object.
            Socket client = (Socket)ar.AsyncState;

            // Complete sending the data to the remote device.
            int bytesSent = client.EndSend(ar);
            Console.WriteLine("Sent {0} bytes to server.", bytesSent);

            // Signal that all bytes have been sent.
            sendDone.Set();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());
        }
    }

}

连接到服务器时,它会响应以下行:

CP3 Console
Warning: Another console session is open

CP3>

当我运行程序时,我得到以下输出:

Socket connected to 10.106.6.60:23
StartSend
WaitForResponse
Receive
Start Read
Bytes read: 13
String CP3 Console

Start Read
Bytes read: 43
String Warning: Another console session is open 

Start Read
Bytes read: 6
String 
CP3>
The thread '<No Name>' (0x1d80) has exited with code 0 (0x0).
The thread '<No Name>' (0x24bc) has exited with code 0 (0x0).

我尝试了不同的阅读流方法,但没有成功。该计划仍然在同一地点挂起。

看起来像读完最后一个字节&#34;&gt;&#34;程序不会重新执行方法&#34; ReceiveCallback&#34;退出循环。

我感觉它有某种方式&#34; ReceiveCallback&#34;正在被调用,但我无法弄清楚client.beginReceive()参数实际上是什么。

2 个答案:

答案 0 :(得分:1)

要扩展Roemer的答案:EndReceive仅在对话终止时才会返回0。这通常意味着已收到带有FIN或RST标志的TCP数据包,这通常是因为对等设备(在您的情况下是服务器)关闭其端点或退出。 (还有其他各种情况;例如,防火墙或中间节点可以生成RST。)

(Roemer写道&#34; BeginReceive永远不会返回零...&#34;,但显然意味着EndReceive,因为BeginReceive会返回IAsyncResult个对象。)

如果对等方没有结束对话结束,EndReceive又不会返回0,那么您永远不会进入回调的else分支调用receiveDone.Set()

从您的描述中并不完全清楚服务器的行为方式,但最后一次发送6个字节显然是一个新行,其后是&#34; CP3&gt;&#34;提示。那时它正等着你的客户发送一些东西。它不打算关闭连接。

TCP是一种字节流服务 - 它不提供记录边界。因此,套接字层无法知道服务器何时发送&#34;,除非服务器关闭连接。您的客户有三种选择:

  1. 在收到服务器输出时解析服务器的输出并识别它何时等待输入(在这种情况下,这意味着识别&#34; CP3&gt;&#34;提示)
  2. 确定服务器已经过了一段任意时间后没有来自服务器的其他数据
  3. 不要担心,只需在收到数据时从服务器输出数据
  4. 第三种选择是最简单的选择。建立连接后,请先进行BeginReceive。然后,在您的回调方法中,如果对话仍处于打开状态且未发生任何错误,请处理您已收到的数据并再次调用BeginReceive

答案 1 :(得分:0)

老实说,微软的这个例子非常糟糕。 通常,除非关闭连接,否则client.EndReceive永远不会返回0。因此,在您的示例中永远不会调用receiveDone.Set。在更实际的示例中,您应该检查ReceiveCallback中的接收数据,并在关键字(如“登录:”)发生时,设置receiveDone并开始发送(例如登录数据)和开始接收再一次等等。您可能还想查看async/await关键字(.net 4.5)并可能升级到Visual Studio社区版:)

有很多关于codeproject的例子或通过谷歌找到的例子(如http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx)。