小编Jus*_*ing的帖子

从C#中的套接字读取

我试图从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 …
Run Code Online (Sandbox Code Playgroud)

c# sockets

2
推荐指数
1
解决办法
4万
查看次数

标签 统计

c# ×1

sockets ×1