简体   繁体   中英

Send unicode String from C# to Java

On C# side, I have this code to send unicode String

    byte[] b = System.Text.Encoding.UTF8.GetBytes(str);
    string unicode = System.Text.Encoding.UTF8.GetString(b);
    //Plus \r\n for end of send string
    SendString(unicode + "\r\n");


   void SendString(String message)
    {
        byte[] buffer = Encoding.ASCII.GetBytes(message);
        AsyncCallback ac = new AsyncCallback(SendStreamMsg);
        tcpClient.GetStream().BeginWrite(buffer, 0, buffer.Length, ac, null);
    }

    private void SendStreamMsg(IAsyncResult ar)
    {
        tcpClient.GetStream().EndWrite(ar);
        tcpClient.GetStream().Flush(); //data send back to java
    }

and this is Java side

     Charset utf8 = Charset.forName("UTF-8");
        bufferReader = new BufferedReader(new InputStreamReader(
                sockServer.getInputStream(),utf8));
     String message = br.readLine();

The problem is I cannot receive unicode string on Java side. How can resolve it?

Your question is a bit ambiguous; You say you cannot receive unicode string on the Java side - Are you getting an error, or are you getting an ASCII string? I'm assuming you are getting an ASCII string, because that is what your SendString() method is sending, but maybe there are additional issues.

Your SendString() method starts out by converting the passed in string to an array of bytes in ASCII encoding; Change ASCII to UTF8 and you should be sending UTF-8:

void SendString(String message)
{
    byte[] buffer = Encoding.UTF8.GetBytes(message);
    AsyncCallback ac = new AsyncCallback(SendStreamMsg);
    tcpClient.GetStream().BeginWrite(buffer, 0, buffer.Length, ac, null);
}

You also seem to have a lot of unnecessary encoding work above this method definition, but without more background I can't guarantee that the encoding work above it is unnecessary...

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