0
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);

这是一个“页面”的割礼(没有结尾)数据。如果在“/ / 1”和“/ / 2”之间写入System.Threading.Thread.Sleep(100),则一切正常。

4

1 回答 1

0

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.

于 2010-07-09T09:17:46.527 回答