tags:

views:

13

answers:

1
private static Socket ConnectSocket(string server, int port)
    {
        Socket s = null;
        IPHostEntry hostEntry = null;

        hostEntry = Dns.GetHostEntry(server);

        foreach (IPAddress address in hostEntry.AddressList)
        {
            IPEndPoint ipe = new IPEndPoint(address, port);
            Socket tempSocket =
                new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);

            tempSocket.Connect(ipe);

            if (tempSocket.Connected)
            {
                s = tempSocket;
                break;
            }
            else
            {
                continue;
            }
        }
        return s;
    }

    //...

    Socket s = ConnectSocket(server, port);

    //...

        do
        {
            bytes = s.Receive(bytesReceived, bytesReceived.Length, 0); // 1
            page = page + Encoding.UTF8.GetString(bytesReceived, 0, bytes); // 2
        }
        while (bytes == 1024);

That's a "page" circumcised (without end) data. If between the "/ / 1" and "/ / 2" write System.Threading.Thread.Sleep(100), then everything works.

A: 

I don't see how that could would work. There are no Receive overload with only three parameters. Also, you have placed bytesReceived.Length in an incorrect position.

s.Receive(bytesReceived, 0, bytesReceived.Length);

Edit: Ohh. You are using the zero for SocketFlags. Don't use magic numbers.

Then there is nothing that says that 1024 bytes must arrive each time, TCP is not built like that. TCP only guarantess that all bytes will arrive, not when or how.

You must either know how many bytes you are going to receive or disconnect on the other end when everything is sent.

jgauffin