I've been working on a Client/Server project and I'm stuck. I'm trying to write a back-up server so I can back-up my files to a remote computer. The problem is when I try to back-up my /home/user file, it gives me the following error on the server side:
java.io.UTFDataFormatException: malformed input around byte ...
I first send the size of the file, then I read the file into a byte array and then is send this byte array at once to the server, who receives it in a byte array it constructed using the file size. Is it a better solution to divide files into chunks or will the error remain?
This usually happens on a .zip file, but it doesn't always happen so that is why I'm confused. Can anyone help me out?
Code:
Server:
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class Server {
private ServerSocket server;
private Socket acceptingSocket;
public Server(int port){
try {
server = new ServerSocket(port);
} catch (IOException e) {
System.out.println("Try again");
}
}
public void run(){
BufferedInputStream buffer = null;
DataInputStream reader = null;
int size = 0;
try {
acceptingSocket = server.accept();
buffer = new BufferedInputStream(acceptingSocket.getInputStream());
reader = new DataInputStream(buffer);
size = reader.readInt();
} catch (IOException e1) {
}
System.out.println("Size: " + size);
for(int j = 0; j < size; j++){
try {
String path = reader.readUTF();
System.out.println("Path: " + path);
long length = reader.readLong();
System.out.println("Length: "+length);
boolean dir = reader.readBoolean();
System.out.println("Dir? " + dir);
path = "/backup" + path;
File file = new File(path);
if(!dir){
int t = file.getAbsolutePath().lastIndexOf("/");
String dirs = file.getAbsolutePath().substring(0, t);
File direcs = new File(dirs);
System.out.println(direcs.mkdirs());
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] b = new byte[(int) length];
int bytes = reader.read(b, 0, (int)length);
if(bytes != -1)
bos.write(b,0,(int)length);
BufferedOutputStream out = new BufferedOutputStream(acceptingSocket.getOutputStream());
DataOutputStream writer = new DataOutputStream(out);
writer.writeUTF("File " + file.getAbsolutePath() + " is created!");
writer.flush();
bos.close();
} else file.mkdirs();
} catch (IOException e) {
System.out.println(e);
}
}
}
public static void main(String[] args){
int port = Integer.parseInt(args[0]);
Server server = new Server(port);
while(true)
server.run();
}
}
Client:
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
public class Client {
private DataInputStream serverToClient;
private Socket client;
private DataOutputStream clientToServer;
private String name;
public Client(String name, int port){
try {
client = new Socket(name, port);
//receive response server
serverToClient = new DataInputStream(client.getInputStream());
//send message to server
clientToServer = new DataOutputStream(client.getOutputStream());
this.name = name;
}
catch (IOException e) {
}
}
public void backUp(String filePath){
File file = new File(filePath);
CopyOnWriteArrayList<File> files = new CopyOnWriteArrayList<File>();
if(file.exists()){
try{
if(file.isDirectory()){
ArrayList<File> f = setToList(file.listFiles());
files.addAll(f);
for(File sendF : files){
if(sendF.isDirectory()){
files.addAll(setToList(sendF.listFiles()));
if(!setToList(sendF.listFiles()).isEmpty()) files.remove(sendF);
}
}
} else{
files.add(file);
}
clientToServer.writeInt(files.size());
for(File fi : files){
boolean dir = false;
if(fi.isDirectory()) dir = true;
clientToServer.writeUTF(fi.getAbsolutePath());
System.out.println(fi.getAbsolutePath());
long length = fi.length();
clientToServer.writeLong(length);
clientToServer.writeBoolean(dir);
System.out.println(length);
if(!dir){
FileInputStream fis = new FileInputStream(fi);
BufferedInputStream bis = new BufferedInputStream(fis);
byte[] buffer = new byte[(int)length];
bis.read(buffer, 0, (int)length);
clientToServer.write(buffer);
System.out.println(serverToClient.readUTF());
bis.close();
fis.close();
}
}
} catch(IOException e){
}
} else System.out.println("File doesn't exist");
}
private ArrayList<File> setToList(File[] listFiles) {
ArrayList<File> newFiles = new ArrayList<File>();
for(File lf : listFiles){
newFiles.add(lf);
}
return newFiles;
}
public static void main(String[] args){
String name = args[0];
int port = Integer.parseInt(args[1]);
System.out.println("Name: " + name + " Port: " + port);
Client client = new Client(name, port);
File file = new File(args[2]);
if(file.exists())client.backUp(args[2]);
else System.out.println("File doesn't exist");
}
}
Related
I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.
I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.
package lab11;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
public class main {
private static final int LISTENING_PORT = 50505;
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "
+ connection.getRemoteSocketAddress());
handleConnection(connection);
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
public static void handleConnection(Socket sok) {
try {
// Scanner in = new Scanner(sok.getInputStream());
InputStream one = sok.getInputStream();
InputStreamReader isr = new InputStreamReader(one);
BufferedReader br = new BufferedReader(isr);
String rootDirectory = "/files";
String pathToFile;
// File file = new File(rootDirectory + pathToFile);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while (!line.isEmpty()) {
request.append(line + "\r\n");
line = br.readLine();
}
// System.out.print(request);
String[] splitline = request.toString().split("\n");
String get = null;
String file = null;
for (String i : splitline) {
if (i.contains("GET")) {
get = i;
String[] splitget = get.split(" ");
file = splitget[1];
}
}
}
OutputStream name = sok.getOutputStream();
Boolean doesexist = thefile.exists();
if (doesexist.equals(true)) {
PrintWriter response = new PrintWriter(System.out);
response.write("HTTP/1.1 200 OK\r\n");
response.write("Connection: close\r\n");
response.write("Content-Length: " + thefile.length() + "\r\n");
response.flush();
response.close();
sendFile(thefile, name);
} else {
System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
}
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally { // make SURE connection is closed before returning!
try {
sok.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
}
}
private static void sendFile(File file, OutputStream socketOut) throws
IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(socketOut);
while (true) {
int x = in.read(); // read one byte from file
if (x < 0)
break; // end of file reached
out.write(x); // write the byte to the socket
}
out.flush();
}
}
So, I don't know what I really did wrong.
When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.
You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.
I am trying to send multiple files from client to server. Files are sent successfully but problem is that when I try to open the receiving file from targetFolder it seems files are corrupted.
Why this type of problem occurring and what is the solution?
How can I solve this by modifying the code to get uncorrupted files?
Server Code:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.zip.Adler32;
import java.util.zip.CRC32;
import java.util.zip.Checksum;
public class Server {
public final static String dirPath = "E:\\targetFolder\\";
public static void main(String[] args){
try{
ServerSocket servsock = new ServerSocket(8080);
Socket socket = servsock.accept();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataInputStream dis = new DataInputStream(bis);
int filesCount = dis.readInt();
File[] files = new File[filesCount];
for(int i = 0; i < filesCount; i++) {
long fileLength = dis.readLong();
String fileName = dis.readUTF();
files[i] = new File(dirPath + fileName);
FileOutputStream fos = new FileOutputStream(files[i]);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] byteArr = new byte[(int)fileLength];
for (int j = 0; j < fileLength; j++) {
int b = bis.read();
bos.write(b);
byteArr[j] = (byte) b;
}
// CheckSum calculating
System.out.println("============================");
System.out.println("File Name: "+fileName);
Checksum checksum = new Adler32();
checksum.update(byteArr,0, byteArr.length);
System.out.println("Check Sum: "+checksum.getValue());
System.out.println("============================");
}
dis.close();
}catch(Exception e){
System.out.println(e);
}
}
}
Client Code:
import java.io.*;
import java.net.Socket;
import java.util.Scanner;
import java.util.zip.Adler32;
import java.util.zip.Checksum;
public class Client {
private static String directory = "E:\\sourceFolder";
public static void main(String[] args) {
try{
Socket sock=new Socket("localhost",8080);
System.out.println("Connecting...");
BufferedOutputStream bos = new BufferedOutputStream(
sock.getOutputStream());
DataOutputStream dos = new DataOutputStream(bos);
File[] files = new File(directory).listFiles();
dos.writeInt(files.length);
for(File file: files) {
long length = file.length();
dos.writeLong(length);
String fileName = file.getName();
dos.writeUTF(fileName);
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
int bt = 0;
byte[] byteArr = new byte[(int)length];
int i = 0;
while((bt = bis.read()) != -1) {
bos.write(bt);
byteArr[i++] = (byte) bt;
}
// CheckSum calculating
System.out.println("============================");
System.out.println("File Name: "+fileName);
Checksum checksum = new Adler32();
checksum.update(byteArr,0, byteArr.length);
System.out.println("Check Sum: "+checksum.getValue());
System.out.println("============================");
bis.close();
}
dos.close();
}catch(Exception e){
System.out.println(e);
}
}
}
How do I send multiple files especially image file and a special string from android as a client socket to a java server socket?
The file is described in a string array where the string is the path where the files are stored.
As for a special string, it will be used as the parent directory on the server, and the uploaded file will be placed there.
I've try a lot of tutorial in SO,ex Stackoverflow
Here's the skeleton I've made.
Updated
I have succesfully transfer those files, but I cannot passed the special strings parent
Android Client
private void handlingUpload(String vehicleNumber) {
System.out.println("PathImage: " + vehicleNumber);
ArrayList<String> list = new ArrayList<String>();
// Get all path each object and sign into list
for (Image image : images) {
list.add(image.getPath());
}
// just prove if list is not emtpty
for (String temp : list) {
System.out.println("FilePath" + temp);
}
// The rules is sending a String vehicleNumber as parent folder
// element in list uploaded Async
Client client = new Client("192.168.8.34", 59090, vehicleNumber);
client.execute();
}
Class to Handle Android Socket
package com.tsurumaru.dzil.clientwarehouse.controllers;
import android.content.ContentResolver;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;
public class Client extends AsyncTask<Void, Void, Void> {
private String address;
private int port;
private String textResponse;
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
OutputStream os = null;
DataOutputStream dos = null;
Context context;
ArrayList<String> list;
public Client(Context context, String address, int port, ArrayList<String> list, String textResponse) {
this.context = context;
this.address = address;
this.port = port;
this.textResponse = textResponse;
this.list = list;
}
#Override
protected Void doInBackground(Void... arg0) {
Socket socket = null;
try {
socket = new Socket(address, port);
//Execute them
DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
//write the number of files to the server
dos.writeInt(list.size());
System.out.println("Do In Background TO Server" + list.size());
dos.flush();
//write file names to the server
for (String temp : list) {
dos.writeUTF(temp);
dos.flush();
}
// write file size to the server
int n = 0;
byte[]buf = new byte[4092];
for (String temp : list) {
File file = new File(temp);
dos.writeLong(file.length());
dos.flush();
}
// write the file
for (String temp : list) {
File file = new File(temp);
FileInputStream fis = new FileInputStream(file);
while ((n = fis.read(buf)) != -1) {
dos.write(buf, 0, n);
dos.flush();
}
}
dos.close();
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
protected void onPostExecute() {
Log.i("ThreadPost", "onPost");
}
}
Java Server
public class MainWindow extends javax.swing.JFrame {
public static void main(String args[]) {
// Create a Socket Server
Thread starter = new Thread(new ServerStart());
starter.start();
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new MainWindow().setVisible(true);
}
});
}
public class ServerStart implements Runnable {
#Override
public void run() {
try {
ServerSocket serverSocket = new ServerSocket(59090);
while (true) {
Socket clientSocket = null;
clientSocket = serverSocket.accept();
// create each thread
Thread listener = new Thread(new ClientHandler(clientSocket));
listener.start();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public class ClientHandler implements Runnable {
Socket socket;
public ClientHandler(Socket clientSocket) {
try {
socket = clientSocket;
} catch (Exception ex) {
textAreaLog.append(ex.getMessage());
}
}
#Override
public void run() {
try {
DataInputStream dis = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
//read the number of files from the client
int number = dis.readInt();
textAreaLog.append("Number of Files to be received: " + number + "\n");
ArrayList<File> files = new ArrayList<File>(number);
ArrayList<Long> size = new ArrayList<Long>(number);
//read file names, add files to arraylist
for (int i = 0; i < number; i++) {
File file = new File(dis.readUTF());
files.add(file);
}
long longSize;
for (int i = 0; i < number; i++) {
longSize = dis.readLong();
size.add(longSize);
}
int n = 0;
byte[] buf = new byte[4092];
for (int i = 0; i < files.size(); i++) {
long fileSize = size.get(i);
textAreaLog.append("Receiving file: " + files.get(i).getPath() + " size: " + fileSize + "\n");
//read file
try (
//create a new fileoutputstream for each new file
FileOutputStream fileOutputStream = new FileOutputStream("D:\\Server Warehouse\\incoming_lokal\\" + files.get(i).getName())) {
//read file
while (fileSize > 0 && (n = dis.read(buf, 0, (int) Math.min(buf.length, fileSize))) != -1) {
fileOutputStream.write(buf, 0, n);
fileSize -= n;
}
fileOutputStream.close();
}
}
} catch (IOException ex) {
textAreaLog.append(ex.getMessage());
} finally {
textAreaLog.append("Thread Is Done " + "\n");
}
}
}
}
Any help it's so appreciated.
Hi every one i'm programming a server client program which transfers file from client to server some files cannot be accepted and i should delete them after a test but the problem is file.delete() doesn't work for me cuz get an error that says file is open i java VM ;
package Serveur;
import java.io.DataInputStream;
import java.io.File;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLException;
public class Serveur {
private static final int PORT =23456;
private ServerSocket serverSkt = null;
private Socket sock = null;
private FileOutputStream fos = null;
private boolean isStopped=false;
private InputStream fis;
private DataInputStream dis = null;
private int idUtil=0;
private String nomFichier = null;
private int taille = 0;
public Serveur() throws ClassNotFoundException, SQLException{
try {
serverSkt = new ServerSocket(PORT);
while(!isStopped){
sock=serverSkt.accept();
if(sock.isConnected()) {
fis=sock.getInputStream();
dis = new DataInputStream(fis);
idUtil=dis.readByte();
taille=dis.readInt();
nomFichier=dis.readUTF();
File fichier = new File("C:/Users/muddo/workspace/PFE/fichiers recu/"+nomFichier);
fos = new FileOutputStream(fichier);
byte[] bytes = new byte[taille];
int count=0;
while((count=dis.read(bytes)) > 0){
fos.write(bytes, 0, count);
}
dis.close();
fis.close();
fos.flush();
fos.close();
sock.close();
new max_allowed_packet();
String ext= fichier.getName().split("\\.")[1];
if(ext.equals("csv") || ext.equals("CSV") || ext.equals("Csv")){
TestCSV tc = new TestCSV(fichier.getAbsolutePath());
if(tc.test()==1){
new ChargerFichierCSV(fichier.getAbsolutePath());
}
else{
fichier.delete();
}
}
else {
new ChargerFichier(fichier.getAbsolutePath(),idUtil);
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void arreterServeur() throws IOException{
if(dis != null)
dis.close();
if(fis != null)
fis.close();
if(fos != null)
fos.close();
if(!sock.isClosed())
sock.close();
if(!serverSkt.isClosed())
serverSkt.close();
isStopped=true;
}
}
The server could be running with another user than the user than owns the file. Did you check file permissions??
File fichier = new File("C:/Users/muddo/workspace/PFE/fichiers recu/"+nomFichier);
The file is owned by user muddo and the server may be running in another user with less privileges. This seems like a bad idea. You should put shared files in a shared folder. Or give permissions to the server user.
I have problem with filetransfer using SocketChannels: client ends to transfer the file, but the server still wait more byte from client. This causes a timeout, and the file will be saved less than a small part. The server remains stucked here: "fileChannel.transferFrom(socketChannel, 0, fileLength);".
Everything that happens before is working properly.
server:
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import javax.imageio.ImageIO;
public class RequestHandler implements Runnable {
private SocketChannel socketChannel;
BufferedReader stringIn;
public RequestHandler(SocketChannel socketChannel) {
this.socketChannel = socketChannel;
// this.serverSocketChannel = socketChannel;
System.out.println("RequestHandler initialized");
}
public static int getLastPush(String dir) {
return new File("./" + dir).listFiles().length + 1;
}
public void run() {
LoadConfig config = null;
try {
config = new LoadConfig();
} catch (IOException e) {
e.printStackTrace();
}
String type = null;
try {
socketChannel.socket().setSoTimeout(10000);
MainServer.log("Client connected from: " + socketChannel);
// Prendere immagine
DataInputStream dis = new DataInputStream(socketChannel.socket().getInputStream());
// Leggo string
stringIn = new BufferedReader(new InputStreamReader(socketChannel.socket().getInputStream()));
// Invio al client
DataOutputStream dos = new DataOutputStream(socketChannel.socket().getOutputStream());
// leggo in ricezione
MainServer.log("Attendo auth");
String auth = stringIn.readLine();
// check auth
MainServer.log("Auth ricevuto: " + auth);
String pass = config.getPass();
if (pass.equals(auth)) {
dos.writeBytes("OK\n");
System.out.println("Client Authenticated");
type = stringIn.readLine();
System.out.println("fileType: " + type);
dos.writeBytes(type + "\n");
Integer i = getLastPush(config.getFolder());
String fileName = i.toString();
System.out.println("fileName: " + fileName);
switch (type) {
case "img":
// transfer image
int len = dis.readInt();
System.out.println("Transfer started.");
byte[] data = new byte[len];
dis.readFully(data);
System.out.println("Transfer ended.");
File toWrite = new File(config.getFolder() + "/" + fileName + ".png");
ImageIO.write(ImageIO.read(new ByteArrayInputStream(data)), "png", toWrite);
dos.writeBytes("http://" + config.getDomain() + "/" + toWrite.getName());
break;
case "file":
// transfer file
System.out.println("Transfer started.");
readFileFromSocket(config.getFolder() + "/" + fileName + ".zip");
System.out.println("Transfer ended.");
System.out.println("Sending link...");
dos.writeBytes("http://" + config.getDomain() + "/" + fileName + ".zip");
break;
default:
}
i++;
System.out.println("Chiudo");
dos.close();
dis.close();
stringIn.close();
} else {
dos.writeBytes("Invalid Id or Password");
System.out.println("Invalid Id or Password");
dos.close();
dis.close();
stringIn.close();
}
socketChannel.close();
} catch (Exception exc) {
exc.printStackTrace();
}
System.out.println("----------");
}
public void readFileFromSocket(String fileName) {
RandomAccessFile aFile = null;
try {
aFile = new RandomAccessFile(fileName, "rw");
FileChannel fileChannel = aFile.getChannel();
long fileLength = Long.parseLong(stringIn.readLine());
System.out.println("File length: " + fileLength);
fileChannel.transferFrom(socketChannel, 0, fileLength);
fileChannel.close();
Thread.sleep(1000);
fileChannel.close();
System.out.println("End of file reached, closing channel");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
client:
import java.awt.AWTException;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import javax.imageio.ImageIO;
public class Uploader {
private BufferedImage img;
private byte[] bytes;
private SocketChannel socketChannel;
private String link;
private String fileName;
DataOutputStream dos;
// Per gli screen parziali
public Uploader(Rectangle r, String ip, int port) throws IOException, AWTException {
SocketChannel socketChannel = createChannel(ip, port);
this.socketChannel = socketChannel;
Rectangle screenRect = new Rectangle(0, 0, 0, 0);
for (GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices()) {
screenRect = screenRect.union(gd.getDefaultConfiguration().getBounds());
}
this.img = new Robot().createScreenCapture(screenRect).getSubimage(r.x, r.y, r.width, r.height);
ByteArrayOutputStream outputArray = new ByteArrayOutputStream();
ImageIO.write(img, "png", outputArray);
outputArray.flush();
this.bytes = outputArray.toByteArray();
outputArray.close();
}
// Per gli screen completi
public Uploader(BufferedImage bi, String ip, int port) throws IOException {
SocketChannel socketChannel = createChannel(ip, port);
this.socketChannel = socketChannel;
this.img = bi;
ByteArrayOutputStream outputArray = new ByteArrayOutputStream();
ImageIO.write(img, "png", outputArray);
outputArray.flush();
this.bytes = outputArray.toByteArray();
outputArray.close();
}
// Per i file
public Uploader(String fileName, String ip, int port) throws UnknownHostException, IOException {
SocketChannel socketChannel = createChannel(ip, port);
this.socketChannel = socketChannel;
// this.socket = new Socket(ip, port);
this.fileName = fileName;
}
public void send(String pass, String type) throws IOException {
dos = new DataOutputStream(socketChannel.socket().getOutputStream());
BufferedReader stringIn = new BufferedReader(new InputStreamReader(socketChannel.socket().getInputStream()));
try {
socketChannel.socket().setSoTimeout(10000);
// send auth
System.out.println("Sending auth");
dos.writeBytes(pass + "\n");
System.out.println("Auth sent: " + pass);
this.link = stringIn.readLine();
// this.link = os.println();
System.out.println("Auth reply: " + link);
if (this.link.equals("OK")) {
System.out.println("Sending type: " + type);
dos.writeBytes(type + "\n");
// Controllo e aspetto che il server abbia ricevuto il type
// corretto
if (stringIn.readLine().equals(type)) {
System.out.println("Il server riceve un: " + type);
switch (type) {
// image transfer
case "img":
System.out.println("Uploading image...");
dos.writeInt(bytes.length);
dos.write(bytes, 0, bytes.length);
dos.flush();
break;
// file transfer
case "file":
sendFile(fileName);
break;
// default case, hmm
default:
break;
}
// return link
System.out.println("Waiting link...");
this.link = stringIn.readLine();
System.out.println("Returned link: " + link);
bytes = null;
} else {
System.out.println("The server had a bad interpretation of the fileType");
}
} else {
System.out.println("Closed");
}
dos.close();
stringIn.close();
socketChannel.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public SocketChannel createChannel(String ip, int port) {
SocketChannel socketChannel = null;
try {
socketChannel = SocketChannel.open();
SocketAddress socketAddress = new InetSocketAddress(ip, port);
socketChannel.connect(socketAddress);
System.out.println("Connected, now sending the file...");
} catch (IOException e) {
e.printStackTrace();
}
return socketChannel;
}
public void sendFile(String fileName) {
RandomAccessFile aFile = null;
try {
File file = new File(fileName);
aFile = new RandomAccessFile(file, "r");
FileChannel inChannel = aFile.getChannel();
long bytesSent = 0, fileLength = file.length();
System.out.println("File length: " + fileLength);
dos.writeBytes(fileLength + "\n");
// send the file
while (bytesSent < fileLength) {
bytesSent += inChannel.transferTo(bytesSent, fileLength - bytesSent, socketChannel);
}
inChannel.close();
Thread.sleep(1000);
System.out.println("End of file reached..");
aFile.close();
System.out.println("File closed.");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public String getLink() {
return link;
}
}
You're losing data in the BufferedReader. If you look at the file that has been received you'll see that part of it is missing at the beginning.
You can't mix buffered and unbuffered input on the same channel. I suggest you use a DataInputStream and use read/writeUTF() to transfer the filename, andread/writeLong() to transfer the length.
I can't imagine why you're using different code to transfer images and other files. It's all bytes.