Reputation: 15
I want to send String from C# to Jave I do it in C# in 2 side like this
Sender: C#
NetworkStream ns1 = _client2.GetStream();
byte[] b = { (byte)2 };//this is the command that sent from client to Server
ns1.Write(b, 0, 1);
string data = "222222222";
byte[] b2 = _AC.GetBytes(data);
ns1.Write(b2, 0, b2.Length);
Reciever C#
Byte[] b = new byte[10];
ns.Read(b, 0, b.Length);
string Data = _AE.GetString(b);
while (ns.DataAvailable)
{
b = new byte[10];
ns.Read(b, 0, b.Length);
Data += _AE.GetString(b);
}
I do some coding with no luck in Java .... like this..
byte b = is.readByte();
byte[] buff= new byte[8];
is.read(buff,0,10);
I receive inside buff[50,50,50,50,50,50,50,50,50]; .....then how to change it to string in java ..... Any help would be great ....thanks
Upvotes: 0
Views: 582
Reputation: 5649
You should specify the encoding of your string! If the c#-program runs on another machine with another operating system than the java-application you might get problems. The java-doc of the String(byte[])-Constructor says:
Constructs a new String by decoding the specified array of bytes using the platform's default charset. ...
Let's say you specify utf-8 string encoding. You should also make sure that c# is also sending an utf-8-string:
byte[] utf8Bytes = System.Text.Encoding.UTF8.GetBytes(myString);
on java-side you should read the bytes as an utf-8-string like this:
String str = new String(buff, "UTF-8");
Upvotes: 2
Reputation: 3963
String has a contsructor for bytes. Just use:
String myNewString = String(buff);
There are several constructors for Strings from bytes, if you don't have any offset, or length concerns then just use the constructor above. If you start to have issues with character sets you can use something like:
String myNewString = null;
try {
myNewString = String(buff , "UTF-8")
} catch (java.io.UnsupportedEncodingException uee) {
//Using an unknown charset will get you here.
uee.printStackTrace();
}
Upvotes: 1
Reputation: 10910
50 is the numeric ASCII value of the character "2". Just take each element of buff
and apply a cast of char to it: (char) buff[0]
, (char) buff[1]
etc.
Upvotes: 0