我寫了一個聊天客戶端,工作正常,直到我決定添加一些文件發送者的東西,應該從客戶端發送文件到服務器。在我爲文件發件人添加行後,它不再顯示消息。爪哇聊天套接字寫入麻煩
我覺得麻煩在這裏,run()中有兩個try語句。
public void run(){
InputStream input = null;
try{
input = socket.getInputStream();
BufferedReader inReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
BufferedWriter outReader = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
//Citeste calea fisierului
String filename = inReader.readLine();
if(filename.equals("")){
//Trimit status READY la client
outReader.write("READY\n");
outReader.flush();
}
FileOutputStream wr = new FileOutputStream(new File("C://tmp/"+filename));
byte[] buffer = new byte[socket.getReceiveBufferSize()];
int bytesReceived = 0;
while((bytesReceived = input.read(buffer)) > 0){
wr.write(buffer,0,bytesReceived);
}
}
catch(IOException e){
Logger.getLogger(ConectareClient.class.getName()).log(Level.SEVERE,null,e);
}
try{
//Inregistreaza firul curent in listaObiecte
listaObiecte.addElement(this);
System.out.println("\n Fir de executie nou");
System.out.println(this.toString());
System.out.println(listaObiecte.toString());
//Bucla
while(true){
//Se citeste mesajul din fluxul de intrare trimis de client
String mesaj = fluxIntrare.readUTF();
//Se transmite mesajul catre toti clientii conectati
transmite(mesaj);
}
}
//Tratare exceptie conexiune
catch (IOException e){
e.printStackTrace();
}
finally{
//Stergere fir curent din listaObiecte
listaObiecte.removeElement(this);
System.out.println("\n Fir de executie inchis");
System.out.println(this.toString());
System.out.println(listaObiecte.toString());
try{
//Inchidere socket
socket.close();
input.close();
}
//Tratare exceptie conexiune
catch (IOException e){
e.printStackTrace();
}
}
}
private static void transmite(String mesaj){
//Enumerare generata de lista firelor de executie
Enumeration enm = listaObiecte.elements();
//Cat timp mai sunt elemente in enumerare
while(enm.hasMoreElements()){
//Se initializeaza cu null referinta firului curent
ConectareClient firDestinatie = null;
//Se protejeaza vectorul firelor de acces simultan
synchronized(listaObiecte){
//Se memoreaza referinta catre firul curent
firDestinatie = (ConectareClient) enm.nextElement();
}
//Referinta valida
if(firDestinatie != null){
try{
//Se protejeaza fluxul de iesire de acces simultan
synchronized(firDestinatie.fluxIesire){
//Scriere mesaj in flux de iesire
firDestinatie.fluxIesire.writeUTF(mesaj);
}
//Mesajul este transmis
firDestinatie.fluxIesire.flush();
}
catch(IOException e){
firDestinatie.stop();
}
}
}
}
在這裏,您可以下載所有的源文件。 http://www.megaupload.com/?d=ULFDBP6M
謝謝。
客戶端可能會發送一個名爲'.. \ windows \ system32 \ user32.dll'的文件嗎? –
好吧,文件發送部分來自我寫的另一個應用程序,它運行得很好,發送所有類型的文件。 –
是的,這正是我試圖告訴你的問題。當客戶端發送包含「..」的文件名時,服務器將覆蓋完全不相關的文件,而不應該這樣做。在創建文件之前,您必須檢查*錯誤的文件名*。 –