首先原諒我的編程說話我不是很善於解釋的東西。Java套接字:如何在發送文件後保持套接字「打開」?
所以,我所做的是創建一個簡單的聊天程序,它能夠通過局域網進行通信。我最近做了它,所以我可以通過插座發送文件
這是一個框架,它有一個按鈕,打開下面顯示的文件選擇器。
public void actionPerformed(ActionEvent arg0) {
JFileChooser chooser = new JFileChooser();
FileNameExtensionFilter filter = new FileNameExtensionFilter(
"Images", "jpg", "gif","png");
FileNameExtensionFilter filter2 = new FileNameExtensionFilter(
"Document", "docx", "doc","pdf","pptx");
chooser.setFileFilter(filter);
chooser.setFileFilter(filter2);
Component parent = null;
int returnVal = chooser.showOpenDialog(parent);
if(returnVal == JFileChooser.APPROVE_OPTION) {
File filesend = new File(chooser.getSelectedFile().getPath());
int count;
OutputStream out;
byte[] buffer = new byte[8192];
try {
c.setMessage("fsendnow");// Sends a command to the server so it knows that im sending a file so it can prepare to receive it
c.msgOut();
out = c.getMyClient().getOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(filesend));
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
out.flush();
}
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
而這不過是接收文件
}else if(line.equalsIgnoreCase("fsendnow")){
byte[] buffer = new byte[8192];
FileOutputStream fos = new FileOutputStream("a.png");
BufferedOutputStream out2 = new BufferedOutputStream(fos);
int count;
InputStream in = client.getInputStream();
while((count=in.read(buffer)) >=0){
fos.write(buffer, 0, count);
}
fos.close();
}else{
cf.printMsg(client.getInetAddress().getHostAddress()+": "+line);
}
問題IM襯片之後我發送一個文件,但它出現在文件夾中,代碼,即時通訊無法打開它,因爲它是「目前正在使用」。我的猜測是,正在運行的程序仍然在向它寫入字節。由於這個套接字仍然「被使用」,我無法對程序做任何事情(發送消息/更多文件)。我嘗試在這裏關閉套接字,但是,我仍然需要它來發送消息,直到我退出聊天窗口。我該怎麼辦?我應該打開一個新的套接字連接嗎?我真的不想這樣做,我真的不想創建一個線程服務器。
while ((count = in.read(buffer)) > 0) {
out.write(buffer, 0, count);
out.flush();
}
//c.getMyClient().close(); CLOSES THE SOCKET
}catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
所以我如何告訴java即時通訊發送文件並停止從「閱讀」圖像。對不起,如果它是一個noob問題。
你最後關閉文件嗎? –
我不知道,但我認爲讀(緩衝區)調用將阻止線程和輸出流文件將永遠不會關閉。 –
爲了解決這個問題,我認爲首先你需要接收字節文件的總數並且在讀取迭代時增加,並且如果字節數達到文件中的字節總數則打破循環。 –