我通过Socket
服务器代码 - (Android应用):
log("sending song to client - " + clientSocket.getInetAddress().toString());
InputStream fileInputStream = new FileInputStream(songFile);
socketDataOutputStream.writeLong(songFile.length());
Thread.sleep(50);
byte[] byteBuffer = new byte[16 * 1024];
int count;
while ((count = fileInputStream.read(byteBuffer)) > 0) {
socketDataOutputStream.write(byteBuffer, 0, count);
}
log("song sent to client - " + clientSocket.getInetAddress().toString());
socketOutputStream.flush();
log("sending a message to client - " + clientSocket.getInetAddress().toString());
socketDataOutputStream.writeUTF("play");
log("message sent to client - " + clientSocket.getInetAddress().toString());
客户代码 - (PC代码):
OutputStream fos = new FileOutputStream(song);
InputStream sis = socket.getInputStream();
DataInputStream dis = new DataInputStream(new BufferedInputStream(sis));
long size = dis.readLong();
int count;
log ("Receiving file");
while (size > 0 && (count = dis.read(buffer, 0, (int) Math.min(buffer.length, size))) != -1) {
fos.write(buffer, 0, count);
size = size - count;
}
fos.close();
log ("File received");
String s;
while ((s = dis.readUTF()) != null) {
log(s);
}
歌曲已成功收到,但之后无法与插座通信!我尝试过不同的方式 - PrintWriter
,write(bytes[])
。没有任何反应 - 客户端代码不会进入第二个while
循环。
我不明白我在做什么错。
答案 0 :(得分:3)
while ((s = dis.readUTF()) != null) {
log(s);
删除它。它没有意义。 readUTF()
不会返回null,并且您不应该只是抛弃输入。
如果应该接收"play"
命令,则应将一个 readUTF()
结果存储到String
然后比较它正确到"play"
。但这个命令是多余的。你可以在收到它后立即播放它,并且你知道它何时发生。
睡眠实际上是浪费时间。删除它。