/**
*
*/
package de.tutorials;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* @author Tom
*
*/
public class ClientServerFileTransferExample {
static ExecutorService executorService = Executors.newCachedThreadPool();
static int cnt;
/**
* @param args
*/
public static void main(String[] args) throws Exception {
executorService.execute(new Runnable() {
public void run() {
try {
final Server server = new Server(8888, new File("c:/tmp/jboss-4.0.3.zip"));
server.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
executorService.execute(new Runnable() {
public void run() {
try {
Client client = new Client("localhost", 8888);
client.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
executorService.execute(new Runnable() {
public void run() {
try {
Client client = new Client("localhost", 8888);
client.start();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
static class Client {
Socket socket;
public Client(String serverName, int port) throws Exception {
this.socket = new Socket(serverName, port);
System.out.println(this + " connected. --> " + this.socket.getLocalSocketAddress());
}
public void start() {
try {
System.out.println(this + " started file transfer.");
InputStream inputStream = this.socket.getInputStream();
byte[] buffer = new byte[16384];
int bytesRead;
OutputStream outputStream = new FileOutputStream("c:/download/"
+ (cnt++) + "_foo.dat");
while ((bytesRead = inputStream.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
socket.close();
System.out.println(this + " finished file transfer.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
static class Server {
ServerSocket serverSocket;
File fileToServe;
/**
* @param port
*/
public Server(int port, File fileToServe) throws Exception {
serverSocket = new ServerSocket(port);
this.fileToServe = fileToServe;
System.out.println("Server ready.");
}
public void start() {
while (true) {
try {
System.out.println("Waiting for clients...");
final Socket socket = serverSocket.accept();
executorService.execute(new Runnable() {
public void run() {
System.out.println("Client: " + socket.getLocalSocketAddress() + " succesfully connected.");
try {
FileInputStream fileInputStream = new FileInputStream(
fileToServe);
byte[] buffer = new byte[16384];
int bytesRead;
OutputStream outputStream = socket
.getOutputStream();
while ((bytesRead = fileInputStream
.read(buffer)) > 0) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
outputStream.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}