1

コンピューター (LocalHost) で実行されているサーバー アプリケーションから 1 つの応答しか受信しない理由を理解するのに苦労しています。このサーバー アプリケーションのソースはありませんが、Java アプリケーションです。送信されるメッセージは xml 構造であり、EoT タグで終了する必要があります。

通信:

  1. クライアントがサーバーに接続します。
  2. クライアントがサーバーにメッセージを送信します。
  3. サーバーは受信したメッセージをクライアントに送信します。
  4. クライアントがサーバーにメッセージを送信します。
  5. サーバーは送信終了文字を送信します。
  6. クライアントがサーバーにメッセージを送信します。
  7. サーバーは送信終了文字を送信します。

これは私のクライアントが接続、送受信する方法です:

public bool ConnectSocket(string server, int port)
{
System.Net.IPHostEntry hostEntry = null;

    try
    {
        // Get host related information.
        hostEntry = System.Net.Dns.GetHostEntry(server);
    }
    catch (System.Exception ex)
    {
            return false;
    }


    // Loop through the AddressList to obtain the supported AddressFamily. This is to avoid
    // an exception that occurs when the host IP Address is not compatible with the address family
    // (typical in the IPv6 case).
    foreach (System.Net.IPAddress address in hostEntry.AddressList)
    {
            System.Net.IPEndPoint ipe = new System.Net.IPEndPoint(address, port);
            System.Net.Sockets.Socket tempSocket = new System.Net.Sockets.Socket(ipe.AddressFamily, System.Net.Sockets.SocketType.Stream, 
                                                                                 System.Net.Sockets.ProtocolType.Tcp);
            tempSocket.Connect(ipe);

            if (tempSocket.Connected)
            {
                m_pSocket = tempSocket;
                m_pSocket.NoDelay = true;
                return true;
            }
            else
                continue;
        }
        return false;
    }
}

public void Send(string message)
{
    message += (char)4;//We add end of transmission character
    m_pSocket.Send(m_Encoding.GetBytes(message.ToCharArray()));
}

private void Recive()
{
    byte[] tByte = new byte[1024];
    m_pSocket.Receive(tByte);
    string recivemessage = (m_Encoding.GetString(tByte));
}
4

1 に答える 1

3

あなたのReceiveコードは非常に間違っているようです。サーバーがメッセージを送信するのと同じ構造でパケットが到着すると想定しないでください。TCP は単なるストリームです。したがって、からの戻り値をキャッチして、受信したバイト数を確認する必要があります。Receive1 つのメッセージの一部、メッセージ全体、複数のメッセージ全体、または 1 つのメッセージの後半と次のメッセージの前半である可能性があります。通常、何らかの「フレーミング」の決定が必要です。これは、「メッセージを LF 文字で分割する」ことを意味するか、「各メッセージの長さの前にネットワーク バイト順の整数である 4 バイトを付ける」ことを意味します。これは通常、フル フレームになるまでバッファする必要があることを意味し、次のフレームの一部であるバッファの最後にあるスペア データについて心配する必要があります。ただし、追加する重要なビット:

int bytes = m_pSocket.Receive(tByte);
// now process "bytes" bytes **only** from tByte, nothing that this
// could be part of a message, an entire message, several messages, or
// the end of message "A", the entire of message "B", and the first byte of
// message "C" (which might not be an entire character)

特に、テキスト形式では、マルチバイト文字が 2 つのメッセージ間で分割される可能性があるため、メッセージ全体がバッファリングされていることを確認するまで、デコードを開始 できません。

受信ループにも問題がある可能性がありますが、それが表示されない (何も呼び出さないReceive) ため、コメントできません。

于 2012-06-11T08:53:38.533 に答える