在我的项目中,我使用DataOutputStream
andDataInputStream
使用带有线程的套接字发送和接收字节。
客户
public void run(){
while(isRunning) {//which is true upon connection of the socket to the server
if(scanner.hasNext()){ // I use a scanner to test the program
dos = new DataOutputStream(new OutputStream(socket.getOutputStream));
byte[] toServer = scanner.next().getBytes();
dos.writeInt(toServer.length);
dos.write(toServer);
}
}
}
服务器
public void run(){
while(isRunning){
if(scanner.hasNext()){
dis = new DataInputStream(new InputStream(socket.getInputStream));
int arrLength = dis.readInt();
byte[] fromClient = new byte[arrLength];
dis.read(fromClient, 0, fromClient.length);
System.out.println("Your string is: " + new String(fromClient));
}
}
}
问题是,当我new String(fromClient)
在服务器端打印出来时,单词/句子的第一个字符总是丢失。当我在客户端输入单词"Test"
时,服务器会打印出"est"
. 但是当我输入" Test"
(开头有一个空格)时,服务器会打印出"Test"
. 我不明白怎么了?我的字节转换有问题吗?