简体   繁体   中英

Java to C# - sending/reading byte from jar server to C# client

I am writing a windows application. am having trouble in sending/receiving bytes from jar file.

jar file sends me a 2 byte [ie. !©]

i can read correctly the 1st byte since it comes within character code 0-127. but for 2nd byte: the extended ASCII say"©" from a jar file, it comes into C# application as

similarly when i send "©" to jar file, jar reads it as

kindly guide me how to solve this problem.

am using this code for reading the byte from jar:

while (m_socClient.Available > 0)
{
    byte[] buffer = new byte[2048];
    int iRx = m_socClient.Receive(buffer);
    char[] chars = new char[iRx];
    System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
    int charLen = d.GetChars(buffer, 0, iRx, chars, 0);
    System.String szData = new System.String(chars);
    byte[] q1 = Encoding.GetEncoding("Windows-1252").GetBytes(szData.Substring(0, 1));
    byte[] r1 = Encoding.GetEncoding("Windows-1252").GetBytes(szData.Substring(1, 1));
    int qu = Convert.ToInt32(q1[0].ToString());
    int re = Convert.ToInt32(r1[0].ToString());   
} 

am using this code for sending the bytes to jar:

var q = Encoding.GetEncoding("Windows-1252").GetString(new byte[] { quotient });
var r = Encoding.GetEncoding("Windows-1252").GetString(new byte[] { remainder });
Object objData_h = q.ToString() + r.ToString();
byte[] byData_h = System.Text.Encoding.ASCII.GetBytes(objData_h.ToString());
m_socClient.Send(byData_h); // send the data to jar file.

Kindly help me please? How can i get the same character code in both C# and java??

I think you are having problems with the encoding. Try doing this:

var q = new char[] { '!', '\u00a9'}; // u00a9 is copyright symbol in unicode.
byte[] b = System.Text.Encoding.ASCII.GetBytes(q); 

Check the byte array and you'll see it holds two bytes, 21 (which is !) and 3f where the second is not what you want. A copyright sign needs more than one byte but ascii are single byte.

Using

byte[] b = System.Text.Encoding.UTF8.GetBytes(q);

Gives you three bytes for the two characters.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM