当我将一些字节放入客户端套接字OutputStream并将它们传递给服务器套接字时,我遇到了一个问题。使用BufferedReader我想读取这些字节,但方法<-128,-1>... ()获取字符,所以当发送范围为<-128,-1>...的字节时,我通常会得到不同的值。如何将这些字符转换为我想要的字节。
public class Client {
public static void main(String[] args) {
Socket s = null;
InputStream is = null;
OutputStream os = null;
try {
s = new Socket("localhost", 3000);
is = s.getInputStream();
os = s.getOutputStream();
int read;
String str = "";
while ((read = is.read()) != '\n') {
str += (char) read;
}
System.out.println(str);
ByteBuffer b = ByteBuffer.allocate(4);
b.order(ByteOrder.BIG_ENDIAN);
b.putInt(430);
byte[] message = b.array();
for (int i = 0; i < message.length; i++) {
System.out.println(message[i] + " ");
}
os.write(message);
} catch (Exception ex) {
}
}
}
class Robot extends Thread {
private Socket s;
public static void main(String[] args) {
ServerSocket ss = null;
try {
ss = new ServerSocket(3000);
while (true) {
Socket s = ss.accept();
Robot srv = new Robot();
srv.s = s;
srv.start();
}
} catch (NumberFormatException numberEx) {
System.out.println("Port of port is not integer");
} catch (IOException ioEx) {
System.out.println("Input connection problem");
} finally {
try {
ss.close();
} catch (IOException ex) {
ex.printStackTrace();
Logger.getLogger(Robot.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
@Override
public void run() {
BufferedReader is = null;
OutputStream os = null;
try {
is = new BufferedReader(new InputStreamReader(s.getInputStream()));
os = s.getOutputStream();
os.write("Send me data:\n".getBytes());
int b;
while ((b = is.read()) != -1) {
System.out.println((byte) b + " ");
}
} catch (Exception ex) {
}
}
}发布于 2014-03-29 19:11:39
读取器将收到的字节转换为字符,并使用系统属性file.encoding (您可以对其进行更改)。
如果你需要字符(字符串),你必须用一种已知的编码(如UTF-8)以字节为单位进行解码和编码。它在客户端和服务器上应该(必须)相同。
如果你只需要字节(不需要字符,不需要字符串),你应该只使用流--不需要读取器
https://stackoverflow.com/questions/22729692
复制相似问题