我有两个通过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循环。
我不明白我做错了什么。
发布于 2017-01-08 06:46:31
while ((s = dis.readUTF()) != null) {
log(s);把这个拿掉。这没有意义。readUTF()不返回null,您不应该只是丢弃输入。
如果这应该是接收"play"命令,则应该将一个readUTF()结果存储到String中,然后正确地将其与"play"进行比较。但这个命令是多余的。一旦你收到了它,你就可以播放它,而且你知道什么时候是。
睡眠简直就是浪费时间。把那个也移开。
https://stackoverflow.com/questions/41529827
复制相似问题