c# - GetString from Byte[] producing different after sending through socket -
so using c# sockets send string 1 process another. send string using byte array. when use getstring(byte[]) in each process during debugging different results when values in byte array same point of debugger. in process send string socket same string when using getstring(). gibberish after receiving data on other size.
to send string use:
string strtosend = "this test"; byte[] stringbytes = system.text.encoding.ascii.getbytes(strtosend); int32 stringsize = stringbytes.length; int32 messagelengthinbytes = sizeof(byte) + sizeof(int32) + sizeof(int32) + stringsize; byte[] message = new byte[messagelengthinbytes]; message[0] = (byte)messagetype.sendstring; unsafe { marshal.copy((intptr)(int32*)&messagelengthinbytes, message, 1, sizeof(int32)); marshal.copy((intptr)(int32*)&stringsize, message, 5, sizeof(int32)); gchandle pinnedarray = gchandle.alloc(stringbytes, gchandletype.pinned); intptr pointer = pinnedarray.addrofpinnedobject(); marshal.copy((intptr)(int32*)&pointer, message, 9, stringsize); pinnedarray.free(); } this.connection.sendmessage(message);
to receive string in other process use:
messagetype = (messagetype)data[dataoffset]; debug.writeline(messagetype.tostring()); dataoffset++; marshal.copy(data, dataoffset, (intptr)(int32*)&messagelengthinbytes, sizeofint32); dataoffset += sizeofint32; int32 stringsize = 0; marshal.copy(data, dataoffset, (intptr)(int32*)&stringsize, sizeofint32); dataoffset += sizeofint32; byte[] stringbytes = new byte[stringsize]; array.copy(data,dataoffset,stringbytes,0,stringsize); dataoffset += stringsize; string recievedstring = system.text.encoding.utf8.getstring(stringbytes);
i gibberish looks like, "h�z\0\0\0\0� \0\0\0\0\0��z".
i sure have no offset problems when using marshal.copy(). mentioned if compare integer values in each byte[] in visual studio debugger have same values! don't understand going on.
you're using ascii.getbytes() when sending, utf8.getstring() when decode recieved byte[].
Comments
Post a Comment