簡體   English   中英

網絡字節順序-電報

[英]Network byte order - telegram

早上好

我正在編寫一個需要通過ATS軟件與Verifone vx820通信的應用程序。

在他們的文檔中,要傳輸數據,它指出:

傳輸數據

我在c#中有一個如何做的例子,在這里:

// Format of ATS telegram:
            //
            //       +---------------------------- ... ---------------------------------+
            //       | xx | xx | xx | xx | Data                                         |
            //       +---------------------------- ... ---------------------------------+
            // Byte  |  0 |  1 |  2 |  3 | 4       ... 
            //       |                   |
            // Field | -- Data Length -- | Data
            //
            // Data length is 4 bytes; network byte order (big-endian)

            try
            {
                // Attempt to make TCP connection to ATS
                Connect();

                // Convert data length to network byte order...
                int iLengthNetworkByteOrder = IPAddress.HostToNetworkOrder(Data.Length);

                // ...then convert it to a byte array
                byte[] DataLength = BitConverter.GetBytes(iLengthNetworkByteOrder);

                // Construct the send buffer, prefixing the data with the data length as shown above
                m_SendBuffer = new byte[DataLength.Length + Data.Length];
                DataLength.CopyTo(m_SendBuffer, 0);
                Data.CopyTo(m_SendBuffer, DataLength.Length);

                // Signal the background thread there is data to send
                m_eventSendDataAvailable.Set();
            }

但是我正在構建這是java。 誰能幫助我轉換為Java。 Java中有簡單的方法可以做到這一點嗎?

有沒有人構建過將ATS與Java結合使用的應用程序,我應該知道什么有用的東西嗎

在Java中,您擁有出色的ByteBuffer類,該類使您可以將普通值(整數,浮點數,雙精度數)編碼/解碼為字節。 ByteBuffer允許您通過order(ByteOrder)方法指定使用的字節order(ByteOrder)

因此,假設您有一個byte[] data ,該byte[] data的長度以32位big endian開頭,如您的示例所示。 你會寫:

// Create a buffer where we'll put the data to send
ByteBuffer sendBuffer = ByteBuffer.allocate(4 + data.length);
sendBuffer.order(ByteOrder.BIG_ENDIAN); // it's the default, but included for clarity

// Put the 4-byte length, then the data itself
sendBuffer.putInt(data.length);
sendBuffer.put(data);

// Extract the actual bytes from our sendBuffer
byte[] dataToSend = sendBuffer.array();

如果情況相反(ATS向您發送帶前綴長度的數據),則代碼將非常相似,但使用getIntget代替。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM