c# - Sending Sockets with binary and ascii data -
i trying integrate company , use sockets not familiar with
i can connected no problem having issues sending data based off want
they want call header record starts message length , 4 other fields integers , want in binary
then want message data want in ascii encoding
i can not figure out how im not sure if should use binary writer first part , try , add ascii
since byte[] dont think can altered after fact
can give me suggestions or samples think work me in matter
my suggestion first create message
class "convertible" , byte[]
type. can create netstream
derives stream
, use send data through specified socket
. it's easy maintain solution not require additional knowledge socket communication @ all.
code example :
// include these namespaces : using system; using system.collections.generic; public class message { int m_messagelength; // other fields char m_otherfield1; char m_otherfield2; char m_otherfield3; char m_otherfield4; // message content assume 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 16 bytes // ascii character 7 bits wide packed 8 bits 1byte // gives 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(); } }
having object can use socket.send
method :
message message = new message("hello world", 1, 3, 3, 7); mesocket.send((byte[])message);
if that's not enough let me know , i'll update answer more details.
Comments
Post a Comment