Skip to content

Instantly share code, notes, and snippets.

@Eng3l
Forked from CarlEkerot/FileClient.java
Last active December 31, 2016 15:57
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Eng3l/2e3973bb71c96d822620b3c752dfa7a9 to your computer and use it in GitHub Desktop.
Save Eng3l/2e3973bb71c96d822620b3c752dfa7a9 to your computer and use it in GitHub Desktop.
Simple java file transfer
package client;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
public class FileClient {
private Socket s;
public FileClient(String host, int port, String file) {
try {
s = new Socket(host, port);
sendFile(file);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendFile(File f) throws IOException {
DataOutputStream dos = new DataOutputStream(s.getOutputStream());
FileInputStream fis = new FileInputStream(f);
byte[] buffer = new byte[4096];
//send filename
byte[] name = f.getName().getBytes();
name = Arrays.copyOf(name, 4096);
dos.write(name);
//send filesize
byte[] size = (f.length() + "").getBytes();
size = Arrays.copyOf(size, 4096);
dos.write(size);
while (fis.read(buffer) > 0) {
dos.write(buffer);
}
fis.close();
dos.close();
}
public static void main(String[] args) {
FileClient fc = new FileClient("localhost", 1988, new File("cat.jpg"));
}
}
package server;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class FileServer extends Thread {
private ServerSocket ss;
public FileServer(int port) {
try {
ss = new ServerSocket(port);
} catch (IOException e) {
e.printStackTrace();
}
}
public void run() {
while (true) {
try {
Socket clientSock = ss.accept();
saveFile(clientSock);
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void saveFile(Socket clientSock) throws IOException {
DataInputStream dis = new DataInputStream(clientSock.getInputStream());
byte[] buffer = new byte[4096];
//request filename
dis.read(buffer, 0, buffer.length);
String file = new String(buffer).trim();
dis.read(buffer, 0, buffer.length);
int filesize = Integer.parseInt(new String(buffer).trim());
FileOutputStream fos = new FileOutputStream(file);
int read = 0;
int totalRead = 0;
int remaining = filesize;
while((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) > 0) {
totalRead += read;
remaining -= read;
System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
}
fos.close();
dis.close();
}
public static void main(String[] args) {
FileServer fs = new FileServer(1988);
fs.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment