Reputation: 85
I´m trying to create a FileEchoServer. I got no Problem sending one File. But if i try to send the file back to the Client, my receiver for the first file is still open. I tried to use outputStream.flush(); on the Client´s Outputstream but its not helping. The code below is server and client in one piece. I hope someone can help me cause i can´t find my fault.
public class Main {
private static int PORT = 5864;
public static void main(String[] args) throws Exception{
String[] options = new String[] {"Server", "Client"};
int response = JOptionPane.showOptionDialog(null, "Start Client or Server?", "Choose",
JOptionPane.DEFAULT_OPTION, JOptionPane.PLAIN_MESSAGE,
null, options, options[0]);
switch (response){
case(0):
Server();
break;
case(1):
Client();
break;
case(-1):
System.exit(0);
}
}
private static void Server() throws Exception{
ServerSocket serverSocket = new ServerSocket(PORT);
Socket socket = serverSocket.accept();
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
File tempFile = File.createTempFile("i dont", "care");
tempFile.deleteOnExit();
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
pushStream(inputStream, fileOutputStream);
fileOutputStream.close();
FileInputStream fileInputStream = new FileInputStream(tempFile);
pushStream(fileInputStream, outputStream);
fileInputStream.close();
inputStream.close();
outputStream.close();
socket.close();
serverSocket.close();
}
private static void Client() throws Exception{
String HOST = "localhost";
Socket socket1 = new Socket(HOST, PORT);
OutputStream outputStream = socket.getOutputStream();
InputStream inputStream = socket.getInputStream();
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\jerem\\Desktop\\Senden Client\\image_test.png");
pushStream(fileInputStream, outputStream);
fileInputStream.close();
FileOutputStream fileOutputStream = new FileOutputStream(new File("C:\\Users\\jerem\\Desktop\\Recieve Client\\dateiAngekommen.png"));
pushStream(inputStream, fileOutputStream);
fileOutputStream.close();
fileInputStream.close();
outputStream.close();
inputStream.close();
socket.close();
}
private static void pushStream(InputStream inputStream, OutputStream outputStream) throws Exception{
byte[] bytes = new byte[16 * 1024];
int count;
while ((count = inputStream.read(bytes)) > 0) {
System.out.println(count);
outputStream.write(bytes, 0, count);
}
System.out.println("Done");
}
}
Upvotes: 1
Views: 23