2017-04-07 52 views
0

我試圖與公司整合,他們用我不熟悉二進制和ASCII數據發送套接字

插座,我可以得到連接沒有問題,但我基於關閉其發送的數據的問題是什麼,他們要

他們想要什麼,他們稱這與消息長度開始 和4個其他字段都是整數頭記錄,他們希望這個二進制

那麼他們想要的信息數據,但希望這ASCII編碼

我無法弄清楚如何做到這一點的IM不知道我是否應該使用二進制作家爲第一部分,並嘗試添加ASCII

,因爲這是一個byte []我不認爲這後就可以改變事實上

誰能給我點建議或者說,他們會認爲這對我在這方面的工作的一些樣品

+0

從接收數據讀取四個字節到一個數組中。使用BitConvert將數組轉換爲int或uint。 BitConverter.ToUInt32(陣列,0);您需要驗證長度是否大於2^31(無符號整數) – jdweng

回答

0

我的建議是先創建一個Message類,這將是「兌換」從和到byte[]類型。然後,您可以創建一個NetStream,該NetStream源自Stream,並使用它通過指定的Socket發送數據。這是一個易於維護的解決方案,根本不需要任何關於套接字通信的額外知識。
代碼示例:

// include these namespaces : 
using System; 
using System.Collections.Generic; 

public class Message 
{ 
    int m_MessageLength; 
    // your other fields 
    char m_OtherField1; 
    char m_OtherField2; 
    char m_OtherField3; 
    char m_OtherField4; 
    // message content as I assume is string 
    string m_MessageContent; 

    public Message(string message, int field1, int field2, int field3, int field4) 
    { 
     m_MessageConten = message; 
     m_OtherField1 = field1; 
     m_OtherField2 = field2; 
     m_OtherField3 = field3; 
     m_OtherField4 = field4; 
    } 

    public static explicit operator byte[](this Message message) 
    { 
     List<byte> buffer = new List<byte>(); 
     // 4 fields each 2bytes wide gives us 16 bytes 
     // ASCII character is 7 bits wide but is packed into 8 bits which is 1byte 
     // gives us the result of (length_of_message * 1byte == length_of_message) 
     buffer.AddRange(BitConverter.GetBytes(8 + m_MessageContent.Length)); 
     buffer.AddRange(BitConverter.GetBytes(m_OtherField1)); 
     buffer.AddRange(BitConverter.GetBytes(m_OtherField2)); 
     buffer.AddRange(BitConverter.GetBytes(m_OtherField3)); 
     buffer.AddRange(BitConverter.GetBytes(m_OtherField4)); 
     buffer.AddRange(Encoding.ASCII.GetBytes(m_MessageContent)); 
     return buffer.ToArray(); 
    } 
} 

有了這個對象,你可以只使用Socket.Send方法:

Message message = new Message("hello world", 1, 3, 3, 7); 
meSocket.Send((byte[])message); 

如果這還不夠,只是讓我知道,我會更新這個答案與更多的細節。

+1

沒有理由同時使用長度前綴和空終止符。您使用空終止符的全部原因是因爲您在開始時無法傳輸消息長度。 –

+0

@ScottChamberlain接縫合理。我會編輯,謝謝:) –

+0

@ m.rogalski快速問題我看你說整數是4字節在這家公司pdf它看起來像有前瞻性或2字節的前4個領域將意味着他們不是整數然後? – quatre432