1

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?

2
  • 3
    What do you mean “cannot receive”? What exactly happens? Commented Oct 25, 2011 at 1:58
  • 4
    Why are you converting the utf-16 string to a utf-8 byte array and then back to a utf-16 string? Commented Oct 25, 2011 at 2:01

1 Answer 1

3

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...

Sign up to request clarification or add additional context in comments.

2 Comments

Oh, so sorry, I'm forgot this line. I fixed it and it work. Thanks
Sr, I didn't know how to use stackoverflow. I just see help. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.