Mam problem z przesyłaniem plików.
W klasie klienta łącze się z serwerem, i przesyłam tablicę bajtów, która reprezentuje wczytany plik. Niestety po odebraniu na serwerze przesłany plik ma 0 bajtów (i generalnie wygląda to tak, jakby przesyłanie się nie skończyło).
klient:
import java.io.*;
import java.net.*;
public class Klient {
public static void main(String[] args) {
try {
Socket s = new Socket("localhost", 6666);
ps = new PrintStream(s.getOutputStream());
os = s.getOutputStream();
String nazwaPliku = "plik.jpg";
File f = new File(nazwaPliku);
if (f.exists()) {
int dlugoscPliku = (int) f.length();
byte[] tablicaBajtow = new byte[dlugoscPliku];
fis = new FileInputStream(f);
bis = new BufferedInputStream(fis);
bis.read(tablicaBajtow, 0, dlugoscPliku);
ps.println(nazwaPliku);
ps.println(dlugoscPliku);
os.write(tablicaBajtow);
}
else
System.out.println("plik nie istnieje");
}
catch (UnknownHostException ex) {
System.out.println(ex);
}
catch (IOException ex) {
System.out.println(ex);
}
finally {
try {
fis.close();
bis.close();
ps.close();
os.close();
}
catch (IOException ex) {
System.out.println(ex);
}
}
}
private static OutputStream os;
private static FileInputStream fis;
private static BufferedInputStream bis;
private static PrintStream ps;
}
serwer:
import java.io.*;
import java.net.*;
public class Serwer {
public static void main(String[] args) {
try {
ServerSocket ss = new ServerSocket(6666);
System.out.println("Serwer uruchomiony.");
while (true) {
Socket s = ss.accept();
is = s.getInputStream();
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
if (s != null) {
System.out.println("Nowe polaczenie");
String nazwaPliku = br.readLine();
System.out.println(nazwaPliku);
String tmp = br.readLine();
int wielkoscPliku = Integer.parseInt(tmp);
System.out.println(wielkoscPliku+"\n");
byte[] tablicaBajtow = new byte[wielkoscPliku];
int tmp2 = 0;
while ((tmp2 = is.read()) != -1) {
is.read(tablicaBajtow, 0, wielkoscPliku);
}
File f = new File("kopia-"+nazwaPliku);
fos = new FileOutputStream(f);
bos = new BufferedOutputStream(fos);
bos.write(tablicaBajtow, 0, wielkoscPliku);
}
}
}
catch (IOException ex) {
System.out.println(ex);
}
finally {
try {
br.close();
is.close();
fos.close();
bos.close();
}
catch (IOException ex) {
System.out.println(ex);
}
}
}
private static BufferedReader br;
private static InputStream is;
private static FileOutputStream fos;
private static BufferedOutputStream bos;
}