【发布时间】:2012-06-19 16:45:11
【问题描述】:
在我的项目中,我使用DataOutputStream 和DataInputStream 使用带有线程的套接字发送和接收字节。
客户
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"。我不明白怎么了?我的字节转换有问题吗?
【问题讨论】:
-
dos.writeInt(toServer)必须是拼写错误,因为它无法编译。 -
还有,客户端/服务器中的
InputStream/OutputStream错字 -
是的,它们是拼写错误……抱歉。
-
首先,应该可以使用
dis.read(fromClient),尽管这不能解决问题 -
另外,
socket.getInputStream()返回一个InputStream,所以new InputStream没有意义。
标签: java multithreading sockets byte