从 C# 中的套接字读取

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47533/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-03 09:59:23  来源:igfitidea点击:

Reading from a socket in C#

提问by Justin Dearing

I am trying to read ASCII text response from a tcp open streaming socket

我正在尝试从 tcp 打开流套接字读取 ASCII 文本响应

This is what I have come up with so far. I want to know what is the best way to do this that includes error handling. Should I also be checking the SocketError after the Receive call in the do loop?

这是我到目前为止想出的。我想知道包括错误处理在内的最佳方法是什么。我还应该在 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();
    }
}

采纳答案by Andy S

Your best bet is probably TcpClient. There's a great sample that does exactly what you're doing right in the .NET Documentation here:

您最好的选择可能是 TcpClient。有一个很好的示例,可以在此处的 .NET 文档中正确执行您正在执行的操作:

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

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

Good luck to you!

祝你好运!