java - FTPClient, multithread upload doesn't work. - java

I am making an application that let's you upload up to 5 files at once to server. I am using apache FTPClient and Filezilla server. when I upload one file at a time it works but when I try to get 2 or more uploads going I get socket exception, the first file that was uploading stops and the new one starts. Here's my UploadThread class:
package uploaduptofive;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import org.apache.commons.net.ftp.FTPClient;
public class ThreadUpload implements Runnable {
FileInputStream inputStream;
long fileLength;
File selFile;
JFrameClass jFrame;
static String fajl;
FTPClient ftpClient;
String ime;
long progress = 0;
int i;
public ThreadUpload(JFrameClass jFrame, FTPClient ftpClient) {
this.jFrame = jFrame;
this.ftpClient = ftpClient;
}
#Override
public synchronized void run() {
i = jFrame.i;
JFileChooser fc = new JFileChooser();
fc.setDialogTitle("Upload file");
fc.setAcceptAllFileFilterUsed(true);
if (fc.showOpenDialog(jFrame) == JFileChooser.APPROVE_OPTION) {
selFile = fc.getSelectedFile();
System.out.println(selFile.length());
Path path = Paths.get(selFile.toString());
fileLength = selFile.length();
fajl = selFile.toString();
ime = selFile.getName();
System.out.println(ime);
try {
upload();
} catch (FileNotFoundException ex) {
Logger.getLogger(ThreadUpload.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(ThreadUpload.class.getName()).log(Level.SEVERE, null, ex);
}
} else {
jFrame.indeksProgress[jFrame.i] = -1;
}
}
protected void upload() throws FileNotFoundException, IOException {
File secondLocalFile = new File(fajl);
String secondRemoteFile = ime;
inputStream = new FileInputStream(secondLocalFile);
OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
byte[] bytesIn = new byte[4096];
int read = 0;
jFrame.nizProgress.get(jFrame.indeksProgress[i]).setValue(0);
while ((read = inputStream.read(bytesIn)) != -1) {
outputStream.write(bytesIn, 0, read);
progress = progress + 4096;
System.out.println("" + ((progress * 100 / fileLength)));
jFrame.nizProgress.get(jFrame.indeksProgress[i]).setValue((int) ((progress * 100 / fileLength)));
}
System.out.println("" + ((((progress) / fileLength) * 100)));
jFrame.nizProgress.get(jFrame.indeksProgress[i]).setValue(100);
inputStream.close();
outputStream.close();
boolean completed = ftpClient.completePendingCommand();
if (completed) {
System.out.println("Uploaded!");
}
}
}
I run threads from class name JFrameClass:
Runnable run = new ThreadUpload(JFrameClass.this, ftpClient);
new Thread(run).start();
here is the error I get:
mar 07, 2013 4:39:01 PM uploaduptofive.ThreadUpload run
SEVERE: null
java.net.SocketException: Software caused connection abort: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:109)
at java.net.SocketOutputStream.write(SocketOutputStream.java:153)
at org.apache.commons.net.io.SocketOutputStream.write(SocketOutputStream.java:71)
at uploaduptofive.ThreadUpload.upload(ThreadUpload.java:79)
at uploaduptofive.ThreadUpload.run(ThreadUpload.java:57)
at java.lang.Thread.run(Thread.java:722)
ThreadUpload.java:57 is where upload(); is, and (ThreadUpload.java:79) is where outputStream.write(bytesIn, 0, read); is.

Apparently, you use the same FtpClient for the two upload processes.
You should re-instantiate a new FtpClient to open a new socket and allow several files being downloaded at the same time:
FtpClient ftpClient = new FtpClient() ;
...
//Opens a new socket
ftpClient.connect("ftp.example.com");
...
Runnable run = new ThreadUpload(JFrameClass.this, ftpClient);
new Thread(run).start();

Related

Cannot reconnect to bluetooth server without restarting bluetooth radio

I have an android client device that will attempt to connect to a bluetooth-enabled server and transmit data to it. So far, it's been working great except for one hitch: whenever I want to reconnect to the server after the connection was terminated, the server does not detect that a request for connection was sent by the client. If I turn off and on the bluetooth radio, and then attempt to reconnect, everything works normally. What am I doing wrong?
Here's the main Class
package org.team2180.scoutingServer;
import java.io.IOException;
import javax.bluetooth.*;
import javax.microedition.io.Connector;
import javax.microedition.io.StreamConnection;
import javax.microedition.io.StreamConnectionNotifier;
import org.json.JSONObject;
import javax.bluetooth.UUID;
public class Server {
public static final UUID serviceUUID = new UUID("94f39d297d6d437d973bfba39e49d4ee", false);
public static String connectionString = "btspp://localhost:" + serviceUUID.toString() +";name=ProblemServer";
static LocalDevice locDev;
public static final JSONObject DATA = new JSONObject();
public static void main(String[] args) {
try {
locDev = LocalDevice.getLocalDevice();
System.out.println("Local Device: '" + locDev.getFriendlyName()+"' # "+locDev.getBluetoothAddress());
StreamConnectionNotifier streamConnNot = startServer();
startListening(streamConnNot);
} catch (Exception e) {
e.printStackTrace();
}
}
public static StreamConnectionNotifier startServer() throws Exception {
if(serverStarted){return null;}
boolean isNowDiscoverable = locDev.setDiscoverable(DiscoveryAgent.GIAC);
System.out.println("Local Device Discoverable: "+Boolean.toString(isNowDiscoverable));
System.out.println("Local Device URI: "+connectionString);
StreamConnectionNotifier streamConnNot = (StreamConnectionNotifier) Connector.open(connectionString);
System.out.println("Server: Created, waiting for clients . . . ");
return streamConnNot;
}
public static void startListening(StreamConnectionNotifier streamConnNot) throws IOException {
while(true) {
StreamConnection connection = streamConnNot.acceptAndOpen();
Thread connectedThread = new Thread(new ConnectionHandler(connection, TEAM_DATA));
System.out.println("Sever: found a client, placed on thread:" + connectedThread.getId());
connectedThread.start();
}
}
}
I handle each connection with its own thread based on this Class, exchanging an initial byte to determine how to handle the connection (send data to the device's database, get data from the device's database)
package org.team2180.scoutingServer;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Iterator;
import javax.microedition.io.StreamConnection;
import javax.bluetooth.RemoteDevice;
import org.json.*;
public class ConnectionHandler implements Runnable {
final StreamConnection connection;
final JSONObject TEAM_DATA;
RemoteDevice remDev;
String deviceIndex;
public ConnectionHandler(StreamConnection connection,JSONObject TEAM_DATA) {
this.connection = connection;
this.TEAM_DATA = TEAM_DATA;
try {
this.remDev = RemoteDevice.getRemoteDevice(connection);
this.deviceIndex = remDev.getFriendlyName(true)+'#'+remDev.getBluetoothAddress();
} catch (IOException e) {
this.remDev = null;
this.deviceIndex = null;
}
}
#Override
public void run() {
try {
OutputStream out = connection.openOutputStream();
InputStream in = connection.openInputStream();
PrintWriter pWriter = new PrintWriter(new OutputStreamWriter(out));
BufferedReader bReader = new BufferedReader(new InputStreamReader(in));
int handshake = in.read();
if(handshake==1) {
System.out.println(deviceIndex+" will now inform you of TOP SECRET_INFO");
updateDatabase(remDev, pWriter, bReader);
System.out.println(deviceIndex+" >\n"+ TEAM_DATA.getJSONObject(deviceIndex).getInt("entryCount"));
}
} catch (Exception e) {
System.out.println(deviceIndex+"'s thread is terminating BADLY!");
try {connection.close();} catch (IOException e1) {e1.printStackTrace();}
return;
}
System.out.println(deviceIndex+"'s thread is terminating!");
return;
}
public void updateDatabase(RemoteDevice remDev, PrintWriter ex, BufferedReader in) throws IOException, JSONException {
//OK!
ex.write(1);
ex.flush();
char[] charData = new char[8192];
in.read(charData);
String data = new String(charData);
connection.close();
//Continue doing other things with data
.
.
.
Here is the Android client code to connect to the server.It is not a thread, and does block, however, this is intentional so that the user waits before leaving the connection radius
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = gatherData();
try{
bS = getSockToServer();
bS.connect();
OutputStream bsO = bS.getOutputStream();
InputStream bsI = bS.getInputStream();
bsO.write(1);//Code upload
bsO.flush();
Log.d("sendButton.onClick","sent condition code 1");
int handRespond = (int)bsI.read();
Log.d("recieved",handRespond+"");
if(handRespond == 1){
bsO.write(text.getBytes("UTF-8"));
bsO.flush();
}
}catch(Exception e){
Log.e("sendButton.onClick",e.toString());
try{
bS.close();
}catch(IOException ioE){
Log.e("sendButton.onClick{SNC}",e.toString());
}
}
}
});
My final goal would be to handle multiple devices at once (hence the usage of threads) and not have to reset the radio every time a device needs to reconnect.
My code extremely crude; I have only been working with bluecove (and bluetooth in general) for two weeks. Any advice/tricks are appreciated!
I can't relive i didn't see this before.
I need to close the socket clientside.
Whoops.

Java - Unzip and Progress Bar

My program uses Tasks from JavaFX to download and unzip files and to show the progress on the screen, by using the updateProgress(workDone, max) method and the progressProperty().bind(observable) method.
It works for Download :
package com.franckyi.lan.installer;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.nio.file.Files;
import java.nio.file.Paths;
import javafx.concurrent.Task;
public class DownloadTask extends Task<Void> {
private String file;
private String url;
public DownloadTask(String dir, String fileurl) {
file = dir;
url = fileurl;
}
#Override
protected Void call() throws Exception {
URLConnection connection = new URL(url).openConnection();
long fileLength = connection.getContentLengthLong();
try (InputStream is = connection.getInputStream();
OutputStream os = Files.newOutputStream(Paths.get(file))) {
long nread = 0L;
byte[] buf = new byte[1024];
int n;
while ((n = is.read(buf)) > 0) {
os.write(buf, 0, n);
nread += n;
updateProgress(nread, fileLength);
}
}
return null;
}
#Override
protected void succeeded(){
System.out.println("Download succeeded");
}
}
But it doesn't work well for Unzip : The file is correctly unzipped but I get a wrong ProgressBar (empty at the end).
package com.franckyi.lan.installer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javafx.concurrent.Task;
public class UnZipTask extends Task<Void>{
private File zipfile;
private File folder;
public UnZipTask(File zipfile, File folder){
this.zipfile = zipfile;
this.folder = folder;
}
#Override
protected Void call() throws Exception {
ZipInputStream zis = new ZipInputStream(
new BufferedInputStream(new FileInputStream(zipfile.getCanonicalFile())));
ZipEntry ze = null;
try {
while ((ze = zis.getNextEntry()) != null) {
File f = new File(folder.getCanonicalPath(), ze.getName());
if (ze.isDirectory()) {
f.mkdirs();
continue;
}
f.getParentFile().mkdirs();
OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
try {
try {
final byte[] buf = new byte[1024];
int bytesRead;
long nread = 0L;
long length = zipfile.length();
while (-1 != (bytesRead = zis.read(buf))){
fos.write(buf, 0, bytesRead);
nread += bytesRead;
System.out.println(nread + "/" + length);
updateProgress(nread, length);
}
} finally {
fos.close();
}
} catch (final IOException ioe) {
f.delete();
throw ioe;
}
}
} finally {
zis.close();
}
return null;
}
#Override
protected void succeeded(){
System.out.println("Unzip succeeded");
}
}
This is what I get in the console :
Download succeeded
1024/91804
2048/91804
2815/91804
362/91804
326/91804
290/91804
386/91804
257/91804
250/91804
588/91804
1101/91804
1613/91804
2128/91804
2646/91804
3159/91804
3672/91804
4185/91804
4701/91804
5214/91804
5731/91804
6243/91804
6755/91804
7272/91804
7793/91804
8326/91804
8862/91804
9379/91804
9897/91804
10411/91804
10927/91804
11442/91804
11956/91804
12437/91804
447/91804
437/91804
978/91804
1525/91804
2040/91804
454/91804
1056/91804
1568/91804
2089/91804
2672/91804
3198/91804
3728/91804
4282/91804
4826/91804
5377/91804
5891/91804
6413/91804
6941/91804
7480/91804
8027/91804
8565/91804
9088/91804
9609/91804
9794/91804
507/91804
1019/91804
1531/91804
2043/91804
2239/91804
134/91804
548/91804
1292/91804
2316/91804
2584/91804
507/91804
837/91804
135/91804
486/91804
1001/91804
1514/91804
2027/91804
2545/91804
3057/91804
3571/91804
4086/91804
4599/91804
5113/91804
5627/91804
6144/91804
6655/91804
7166/91804
7679/91804
8196/91804
8710/91804
9229/91804
9745/91804
10259/91804
10773/91804
11288/91804
11802/91804
12321/91804
12834/91804
13348/91804
13864/91804
14378/91804
14893/91804
15407/91804
15918/91804
16431/91804
16944/91804
17458/91804
17971/91804
18484/91804
18997/91804
19508/91804
20021/91804
20535/91804
21047/91804
21560/91804
22072/91804
22584/91804
23096/91804
23609/91804
24122/91804
24638/91804
25149/91804
25664/91804
26176/91804
26689/91804
27203/91804
27715/91804
28227/91804
28739/91804
29251/91804
29764/91804
30277/91804
30789/91804
31301/91804
31813/91804
32325/91804
32838/91804
33306/91804
33819/91804
34333/91804
34846/91804
35357/91804
35869/91804
36381/91804
36894/91804
37407/91804
37922/91804
38435/91804
38948/91804
39460/91804
39972/91804
40488/91804
41002/91804
41514/91804
42028/91804
42540/91804
43052/91804
43566/91804
44079/91804
44594/91804
45105/91804
45619/91804
46132/91804
46644/91804
47156/91804
47668/91804
48180/91804
48692/91804
49204/91804
49716/91804
50228/91804
50741/91804
51252/91804
51765/91804
52277/91804
52790/91804
53305/91804
53821/91804
54335/91804
54852/91804
55365/91804
55881/91804
56396/91804
56442/91804
545/91804
1287/91804
2311/91804
2584/91804
507/91804
845/91804
4/91804
Unzip succeeded
Can someone help me ?
It is because you use length of compressed zipFile as the maximum, and the count of bytes raeded from each uncompressed zipEntry as the postion - the size of compressed file is in most cases different from the uncompressed one, also you can have multiple files in the zip package - so the progres will jump from 0 to some value (the size of actual zipEntry not the compressed zipFile length) for each one in this case. To have the actual position in a zip file, get the reference to FileChannel from the FileInputStream, using this method: FileInputStream#getChannel();
then when it comes to update the progres do:
updateProgress(channel.position(), length);
This will update the progress bar according to the actual position that was readed in the zipFile (not the size of uncompressed content).
It could be something like:
package com.franckyi.lan.installer;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import javafx.concurrent.Task;
public class UnZipTask extends Task<Void>{
private File zipfile;
private File folder;
public UnZipTask(File zipfile, File folder){
this.zipfile = zipfile;
this.folder = folder;
}
#Override
protected Void call() throws Exception {
FileInputStream is = new FileInputStream(zipfile.getCanonicalFile());
FileChannel channel = is.getChannel();
ZipInputStream zis = new ZipInputStream(new BufferedInputStream(is));
ZipEntry ze = null;
try {
while ((ze = zis.getNextEntry()) != null) {
File f = new File(folder.getCanonicalPath(), ze.getName());
if (ze.isDirectory()) {
f.mkdirs();
continue;
}
f.getParentFile().mkdirs();
OutputStream fos = new BufferedOutputStream(new FileOutputStream(f));
try {
try {
final byte[] buf = new byte[1024];
int bytesRead;
long nread = 0L;
long length = zipfile.length();
while (-1 != (bytesRead = zis.read(buf))){
fos.write(buf, 0, bytesRead);
nread += bytesRead;
System.out.println(nread + "/" + length);
updateProgress(channel.position(), length);
}
} finally {
fos.close();
}
} catch (final IOException ioe) {
f.delete();
throw ioe;
}
}
} finally {
zis.close();
}
return null;
}
#Override
protected void succeeded(){
System.out.println("Unzip succeeded");
}
}

Java - how to print the PDF to a specific printer?

I have 5 printers in Windows 8.1 and the PDF file is not in local system its generated in PHP server.
Question. how can i get the PDF file from the server and print to a specific printer?
I am trying with Apache PDFBox 2.0.0
EDIT:
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import javax.print.DocPrintJob;
import javax.print.PrintService;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;
public class JPrint {
public static boolean saveFile(URL url, String file) throws IOException {
boolean download_status = false;
System.out.println("[OK] - open");
InputStream in = url.openStream();
FileOutputStream fos = new FileOutputStream(new File(file));
System.out.println("[OK] - reading file...");
int length = -1;
byte[] buffer = new byte[1024];
while ((length = in.read(buffer)) > -1) {
fos.write(buffer, 0, length);
}
fos.close();
in.close();
download_status = true;
System.out.println("[OK] - downloaded");
return download_status;
}
public static void main(String[] args) throws IOException, PrinterException {
String downloaded_filename = "C:/Users/tpt/Downloads/pdf.pdf";
String download_pdf_from = "https://github.com/msysgit/msysgit/releases/download/Git-1.9.2-preview20140411/Git-1.9.2-preview20140411.exe";
String downloaded_filename_open_as_pdf = "C:\\Users\\tpt\\Downloads\\pdf.pdf";
String printerNameDesired = "DYMO LabelWriter 450"; // Brother HL-6180DW series
// Get printers
PrintService[] services = PrinterJob.lookupPrintServices();
DocPrintJob docPrintJob = null;
try{
URL url = new URL(download_pdf_from);
if(saveFile(url, downloaded_filename)) {
try {
PDDocument pdf = PDDocument.load(new File(downloaded_filename_open_as_pdf));
PrinterJob job = PrinterJob.getPrinterJob();
for (int i = 0; i < services.length; i++) {
if (services[i].getName().equalsIgnoreCase(printerNameDesired)) {
docPrintJob = services[i].createPrintJob();
}
}
job.setPrintService(docPrintJob.getPrintService());
job.setPageable(new PDFPageable(pdf));
//docPrintJob = service[i].createPrintJob();
job.print();
} catch (Exception e) {
System.out.println("[FAIL]" + e);
}
} else {
System.out.println("[FAIL] - download fail");
}
} catch (Exception ae) {
System.out.println("[FAIL]" + ae);
}
}
}
This gives you back a list of available printers:
PrintService[] services = PrinterJob.lookupPrintServices();
You can loop through this array and select the printer by name (services[i].getName())

Download Manager In java using multi threading

as you have seen before I'm working on a download manager in java, I have asked This Question and I have read This Question But These hadn't solve my problem. now I have wrote another code in java. but there is a problem. when download finishes file is larger than it's size and related software can't read it
This is image of my code execution :
as you see file size is about 9.43 MB
This is My project directory's image:
as you see my downloaded filesize is about 13 MB
So what is my Prooblem?
here is my complete source code
Main Class:
package download.manager;
import java.util.Scanner;
/**
*
* #author Behzad
*/
public class DownloadManager {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter url here : ");
String url = input.nextLine();
DownloadInfo information = new DownloadInfo(url);
}
}
DownloadInfo Class:
package download.manager;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DownloadInfo {
private String downloadUrl;
private String fileName;
private String fileExtension;
private URL nonStringUrl;
private HttpURLConnection connection;
private int fileSize;
private int remainingByte;
private RandomAccessFile outputFile;
public DownloadInfo(String downloadUrl) {
this.downloadUrl = downloadUrl;
initiateInformation();
}
private void initiateInformation(){
fileName = downloadUrl.substring(downloadUrl.lastIndexOf('/') + 1, downloadUrl.length());
fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length());
try {
nonStringUrl = new URL(downloadUrl);
connection = (HttpURLConnection) nonStringUrl.openConnection();
fileSize = ((connection.getContentLength()));
System.out.printf("File Size is : %d \n", fileSize);
System.out.printf("Remain File Size is : %d \n", fileSize % 8);
remainingByte = fileSize % 8;
fileSize /= 8;
outputFile = new RandomAccessFile(fileName, "rw");
} catch (MalformedURLException ex) {
Logger.getLogger(DownloadInfo.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(DownloadInfo.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.printf("File Name is : %s\n", fileName);
System.out.printf("File Extension is : %s\n", fileExtension);
System.out.printf("Partition Size is : %d MB\n", fileSize);
int first = 0 , last = fileSize - 1;
ExecutorService thread_pool = Executors.newFixedThreadPool(8);
for(int i=0;i<8;i++){
if(i != 7){
thread_pool.submit(new Downloader(nonStringUrl, first, last, (i+1), outputFile));
}
else{
thread_pool.submit(new Downloader(nonStringUrl, first, last + remainingByte, (i+1), outputFile));
}
first = last + 1;
last += fileSize;
}
thread_pool.shutdown();
try {
thread_pool.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (InterruptedException ex) {
Logger.getLogger(DownloadInfo.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
and this is my downloader class:
package download.manager;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author Behzad
*/
public class Downloader implements Runnable{
private URL downloadURL;
private int startByte;
private int endByte;
private int threadNum;
private RandomAccessFile outputFile;
private InputStream stream;
public Downloader(URL downloadURL,int startByte, int endByte, int threadNum, RandomAccessFile outputFile) {
this.downloadURL = downloadURL;
this.startByte = startByte;
this.endByte = endByte;
this.threadNum = threadNum;
this.outputFile = outputFile;
}
#Override
public void run() {
download();
}
private void download(){
try {
System.out.printf("Thread %d is working...\n" , threadNum);
HttpURLConnection httpURLConnection = (HttpURLConnection) downloadURL.openConnection();
httpURLConnection.setRequestProperty("Range", "bytes="+startByte+"-"+endByte);
httpURLConnection.connect();
outputFile.seek(startByte);
stream = httpURLConnection.getInputStream();
while(true){
int nextByte = stream.read();
if(nextByte == -1){
break;
}
outputFile.write(endByte);
}
} catch (IOException ex) {
Logger.getLogger(Downloader.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
This file is MP4 for as you seen, but Gom can't play it
Would you please help me?
OoOoOopppps finally I found what is the problem , It's all on seek method. because i have a file and 8 threads. so seek method changes the cursor repeatedly and make larger file and unexecutable file :), But I'm so sorry . I can't show whole code :)

How to create a simple Server Client Application Using RUDP in Java?

I was working on a simple application to transfer files between two machines using UDP, but that turned out to be lossy and unreliable, so while searching the Internet I found this project named Simple Reliable UDP here, but they don't have any documentation or any example code. So if there is any who can help me with this code I will be grateful because I'm newbie in Java. I started with writing simple server client app, but I got address already bind exception. To make clear I want to use UDP connections only that's why I'm trying to implement ReliableServerSocket and ReliableSocket.
package stackoverflow;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class udpServer implements Runnable{
ReliableServerSocket rss;
///ocket rs;
ReliableSocket rs;
public udpServer() throws IOException {
rss= new ReliableServerSocket(9876);
}
public void run(){
while (true){
try {
rs=(ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println(""+rs.getInetAddress());
BufferedReader inReader = new BufferedReader (new InputStreamReader (rs.getInputStream()));
//BufferedWriter outReader = new BufferedWriter (new OutputStreamWriter (rs.getOutputStream()));
String str= ""+inReader.readLine();
if(str.contains("UPLOAD")){
System.out.println("Client wants to upload file");
}else if(str.contains("D1")){
System.out.println("Client wants to download file");
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String args[]) throws Exception
{
System.out.println("UDP Server Executed");
Thread t= new Thread( new udpServer());
t.start();
}
}
Client Code here
package stackoverflow;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UdpFileClient {
BufferedWriter outReader;
ReliableSocket server;
public UdpFileClient(boolean b1, boolean b2) throws IOException {
if (b1) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("D1");
System.out.println("Download Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
if (b2) {
server = new ReliableSocket("127.0.0.1", 9876);
outReader = new BufferedWriter(new OutputStreamWriter(server.getOutputStream()));
outReader.write("UPLOAD");
System.out.println("Upload Req Sent From Client");
server.close();
outReader.flush();
outReader.close();
}
}
public static void main(String args[]) throws Exception {
System.out.println("UDP CLient Executed");
new UdpFileClient(true, true);
}
}
I already know I can use TCP/IP, but it is kind of requirement for the project to use UDP. If any other way to send files in lossless way using UDP with good speed will also be helpful.
Thanks in advance!!
I tried RUDP and found that i was not printing my output, i know this is a silly mistake.
UDP Client
package UDPClient;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtestc {
ReliableSocket server;
public UDPtestc() throws IOException {
server = new ReliableSocket();
server.connect(new InetSocketAddress("127.0.0.1", 9876));
byte[] buffer = new byte[1024];
int count,progress=0;
InputStream in = server.getInputStream();
while((count=in.read(buffer)) >0){
progress+=count;
System.out.println(""+progress);
}
server.close();
}
public static void main(String[] args) throws IOException {
new UDPtestc();
}
}
UDPserver
package UDPServer;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.RandomAccessFile;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.rudp.ReliableServerSocket;
import net.rudp.ReliableSocket;
/**
*
* #author Nika
*/
public class UDPtests implements Runnable {
ReliableServerSocket rss;
ReliableSocket rs;
String file;
FileInputStream bin;
public UDPtests() throws IOException {
rss = new ReliableServerSocket(9876);
Thread serverthread = new Thread(this);
serverthread.start();
}
public void run() {
while (true) {
try {
rs = (ReliableSocket)rss.accept();
System.out.println("Connection Accepted");
System.out.println("" + rs.getRemoteSocketAddress());
file = "";
Long size=0L;
file += "10MB.txt";
size+=10*1024*1024;
RandomAccessFile r1= new RandomAccessFile(file,"rw");
r1.setLength(size);
byte[] sendData = new byte[1024];
OutputStream os = rs.getOutputStream();
//FileOutputStream wr = new FileOutputStream(new File(file));
bin= new FileInputStream(file);
int bytesReceived = 0;
int progress = 0;
while ((bytesReceived = bin.read(sendData)) > 0) {
/* Write to the file */
os.write(sendData, 0, bytesReceived);
progress += bytesReceived;
System.out.println(""+progress);
}
} catch (IOException ex) {
Logger.getLogger(udpServer.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public static void main(String[] args) throws IOException {
new UDPtests();
}
}
Soon i will post other tuts on RUDP if it will be possible.

Categories

Resources