当前位置:  开发笔记 > 编程语言 > 正文

从C#中的套接字读取

如何解决《从C#中的套接字读取》经验,为你挑选了1个好方法。

我试图从tcp开放流式套接字读取ASCII文本响应

这是我到目前为止所提出的.我想知道包含错误处理的最佳方法是什么.我应该在do循环中的Receive调用之后检查SocketError吗?

IPEndPoint ep = new IPEndPoint(IPAddress.Parse("192.168.1.1"), 9000);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.SendTimeout = 5000;
sock.ReceiveTimeout = 5000;
if (null != sock)
{
    try
    {
        sock.Connect(ep);
        if (sock.Connected)
        {

            // Blocks until send returns.
            int bytesSent = sock.Send(buffer);
            Console.WriteLine("Sent {0} bytes.", bytesSent);
            //get the first 4 bytes, should be the lenngth of the rest of the response.
            byte[] response = new byte[4];
            int bytesRec = sock.Receive(response);
            int totalBytesRec = 0;
            if (4 == bytesRec)
            {
                int len = BitConverter.ToInt32(response, 0);
                response = new byte[len];
                Console.WriteLine("Trying to get {0} bytes.", len);
                bytesRec = 0;

                do
                {
                    bytesRec = sock.Receive(response);
                    totalBytesRec += bytesRec;
                    forecast += Encoding.ASCII.GetString(response, 0, bytesRec);
                } while (totalBytesRec < len && bytesRec > 0);

                if (totalBytesRec != len)
                    throw new Exception("The total bytes recieved from manager did not equal the expected bytes");
            }
            else
                throw new Exception("Unable to get the response size from the manager");


            Console.WriteLine("Received {0} bytes.", totalBytesRec);
        }

    }
    catch (SocketException ex)
    {
        Console.WriteLine("{0} Error code: {1}.", ex.Message, ex.ErrorCode);
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
    finally
    {
        sock.Shutdown(SocketShutdown.Both);
        sock.Close();
    }
}

Andy S.. 5

你最好的选择可能是TcpClient.这里有一个很棒的示例,它可以完成您在.NET文档中所做的工作:

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx

祝你好运!



1> Andy S..:

你最好的选择可能是TcpClient.这里有一个很棒的示例,它可以完成您在.NET文档中所做的工作:

http://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.aspx

祝你好运!

推荐阅读
jerry613
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有