public class Receiver implements Runnable {
private int port;
public Receiver(int port) {
this.port = port;
}
@Override
public void run() {
Socket socket = null;
BufferedOutputStream bos = null;
try {
InetAddress adresa = InetAddress.getByName("localhost");
System.out.println("klient sa pripaja na adresu: " + adresa);
socket = new Socket(adresa, this.port);
System.out.println("socket = " + socket);
while (true) {
BufferedReader input = new BufferedReader(
new InputStreamReader(socket.getInputStream()));
String name = input.readLine();
/// while (???????) {}
if (name.equals("poison.pill")) {// null pointer exception
bos.close();
socket.close();
break;
}
int filesize = 1400;
int bytesRead;
byte[] bytearray = new byte[filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(name);
bos = new BufferedOutputStream(fos);
while ((bytesRead = is.read(bytearray)) != -1) {
bos.write(bytearray, 0, bytesRead);
bos.flush();
}
}
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
如果有误解我会解释。
答案 0 :(得分:0)
也许我不理解你,但你想要什么?看看你的代码,你可以看到
input.readLine()
while ((bytesRead =
is.read(bytearray)) != -1) {
读取所有!!!! 数据-1表示流为空NullPointer
。解决方案,等到一些数据到达流...