I have a multithreaded program java java socket and I receive the information bizare. like this ¤¤¤¤¤¤23456718900263678722¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤
public void run()
{
try {
byte[] bs = new byte[64];
// read data into buffer
dataReception.read(bs);
// for each byte in the buffer
for (byte b:bs)
{
// convert byte into character
char c = (char)b;
// print the character
System.out.print(c);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
The problem is here:
// read data into buffer
dataReception.read(bs);
Read doesn't read exactly that amount of bytes that you want to have in that array. It can read any number of bytes. Therefore you always have to check the return value of the read operation; and only when all expected bytes were read ... you should continue!
The reason that your output looks like garbage is this not that you would be receiving special characters.
What happens is:
This can be verified by printing your array before reading. You will see that only contains those "special" characters.
如果您期望正好是 64 个字节,请使用readFully()
而不是read(),
或者至少注意它的返回值。
Try:
public void run()
{
try {
byte[] bs = new byte[64];
// read data into buffer
int readed = dataReception.read(bs);
// for each byte in the buffer
for (int n=0; n<readed;n++)
{
byte b=bs[n];
// convert byte into character
char c = (char)b;
// print the character
System.out.print(c);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
DataInputStream is usually used when textual information need to be shared over socket. Use DataInputStream.readUTF() method if the transferred data is sent using DataOutputStream.writeUTF(String str) from the other end. DataInputStream and DataOutputStream sends two byte(unsigned) length of data before sending actual data.
final String data = din.readUTF();
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.