简体   繁体   English

Java到C#-从jar服务器向C#客户端发送/读取字节

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

I am writing a windows application. 我正在编写Windows应用程序。 am having trouble in sending/receiving bytes from jar file. 从jar文件发送/接收字节时遇到麻烦。

jar file sends me a 2 byte [ie. jar文件向我发送了2个字节[即 !©] !©]

i can read correctly the 1st byte since it comes within character code 0-127. 我可以正确读取第一个字节,因为它位于字符代码0-127之内。 but for 2nd byte: the extended ASCII say"©" from a jar file, it comes into C# application as 但是对于第二个字节:来自jar文件的扩展ASCII说“©”,它作为进入C#应用程序。

similarly when i send "©" to jar file, jar reads it as 类似地,当我向jar文件发送“©”时,jar将其读取为

kindly guide me how to solve this problem. 请指导我如何解决这个问题。

am using this code for reading the byte from jar: 我正在使用此代码从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: 我正在使用以下代码将字节发送到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?? 我如何在C#和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. 检查字节数组,您会看到它包含两个字节,21(即!)和3f,其中第二个不是您想要的字节。 A copyright sign needs more than one byte but ascii are single byte. 版权标志需要多个字节,而ascii是单个字节。

Using 使用

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

Gives you three bytes for the two characters. 给您两个字符三个字节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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