java tcp server to android device - java

i am trying to make a java server that will send images stored in a database to android device.
for now am trying with simple image that stored on the hard disk for the server to send.
my question is can i send an image from java server as a byte array to android via TCP sockets.

Yes, you can, using TCP sockets.
Read the file as bytes and send it as bytes, don't try to load it as a BufferedImage.
Then, on the receiving end, use a function that allows you to load an image from an array of bytes.

Sure, you can, but you will need to invent your own protocol for that. You may find using HTTP more, either setting up a web-server like Tomcat with your application deployed there, or use something embedded like Jetty

The fastest and easiest approach for sending image is as follows...
Try this
// Server Side code for image sending
ServerSocket servsock = new ServerSocket(13250);
System.out.println("Main Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
File myFile = new File ("\sdcard\ab.jpg");
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);*/
byte [] mybytearray =new byte[count];
System.arraycopy(Copy, 0, mybytearray, 0, count);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
os.close();
sock.close();
servsock.close();
//Client side code for image reception
try
{
int filesize=6022386; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
// localhost for testing
ServerSocket servsocket = new ServerSocket(13267);
System.out.println("Thread Waiting...");
Socket socket = servsocket.accept();
System.out.println("Accepted connection : " + socket);
System.out.println("Connecting...");
File f=new File("\sdcard\ab.jpg");
f.createNewFile();
// receive file
byte [] mybytearray = new byte [filesize];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream(f);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
count=current;
Copy=mybytearray.clone();
bos.write(mybytearray, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
System.out.println(end-start);
bos.close();
fos.close();
socket.close();
servsocket.close();
}
} catch(IOException e)
{
System.out.println("errorr");
}

Related

UDP File Transfer Java

I know UDP is not reliable and should not be used to send files but I have been asked to do that inside of a small part of an application for a small college assignment. For some reason my application freezes when I run the code to upload a file from client to server. Could anyone please help tell me what I'm doing wrong?
Client:
String hostName = hostNameTxt.getText();
String portAsString = portNumTxt.getText();
int portNum = Integer.parseInt(portAsString);
String sentFilePath = "c:/Documents/test.txt";
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(portNum);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept(); //failing here I think
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (sentFilePath);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = sock.getOutputStream();
System.out.println("Sending " + sentFilePath + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
catch (IOException ex) {
Logger.getLogger(Client1Interface.class.getName()).log(Level.SEVERE, null, ex);
System.out.println(ex);
} finally {
if (servsock != null) try {
servsock.close();
} catch (IOException ex) {
Logger.getLogger(Client1Interface.class.getName()).log(Level.SEVERE, null, ex);
}
}
Server:
String recievedFilePath = "c:/Documents/source.txt";
String hostName = "localhost";
int portNum = 7;
int fileSize = 6022386;
try{
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(hostName, portNum);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [fileSize];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(recievedFilePath);
bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File " + recievedFilePath
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
catch(Exception ex){
ex.printStackTrace( );
System.out.println("Error Uploading File");
}
You should try to use another port. The IP port 7 is blocked for the echo service, which will simply send you the same data back.
You should use ports above 1024. Otherwise you need superuser right from you OS to use this port.
The naming of you app is a little bit confusing. Normally the server should provide a ServerSocket on a not already used port and listen. The client must connect with a regular Socket to this port and send the data.
I've been testing your program (both server and client running in the same host), and it works. Still, I've to warn you about some important details (basically all of them have been already told in comments):
Conceptual details
The APIs chosen (java.net.Socket and java.net.ServerSocket) are TCP socket implementations, and not UDP. The UPD APIs are java.net.DatagramSocket and java.net.DatagramPacket.
The first program is no doubt the server, and the second is the client.
Technical details
You have to start first the server, and then, the client.
Server and client must run on different JVMs, so you have to run each one on a different process, either in a command shell or either by running it from your IDE.
(as Lars Repenning said) You have to use any available port over 1024, for example 3000.
Minor technical details
Do not allocate a buffer as big as the file size. To write the data out to a File, you should use the buffering technique: Use a small buffer (4096 bytes or multiple) and on each iteration, fill it with InputStream.read and write it with OutputStream.write. You will avoid memory problems and also will save yourself the need to know a priori the file size.

Sending file from Server to Client java

When I'm sending a small file, everything works fine. But when I'm trying to send a file about 5 megabytes, server throws such exception: java.net.socketexception: connection reset by peer: socket write error.
This is a part of my Server:
try {
File myFile = new File("E:\\work\\java\\in.pdf");
long len = myFile.length();
byte[] mybytearray = new byte[(int) myFile.length()];
output = new PrintStream(serviceSocket.getOutputStream());
output.println(clientCounter + " " + len);
bis = new BufferedInputStream(new FileInputStream(myFile));
bis.read(mybytearray, 0, mybytearray.length);
os = serviceSocket.getOutputStream();
os.write(mybytearray, 0, mybytearray.length);
os.flush();
serviceSocket.close();
}
catch(IOException e) {
System.out.println(e);
}
You're assuming that read() fills the buffer, and no doubt you're making the same mistake in the client as well. You have to loop.

Sysout list of files and transfer files from a directory in java

I'm trying to figure out how to get a list of files on the server and how to download them individually. Can anyone guide me in the right direction?
I'm getting file permissions error or (is a directory errors), thanks
UPDATE:
The error is
Exception in thread "main" java.io.FileNotFoundException: /myClientFiles (Permission denied)
at java.io.FileOutputStream.open(Native Method)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at
xxxxxxpackegename.com.fr(Client.java:38)
Client.java
public class Client {
private static final int PORT = 2665;
private static String HOST = "localhost";
public static void main(String[] args) throws UnknownHostException, IOException {
int filesize = 5000000; //buffer size 5mb
int bytesRead;
int currentTotalNumberOfBytes = 0;
//connect to port on server - server waits for this after running socket.accept() in the Server class
Socket socket = new Socket(HOST, PORT);
byte[] byteArray = new byte[filesize]; //create a byte array of 5mb
InputStream inputStream = socket.getInputStream(); //channel to write to server
FileOutputStream fileOutStream = new FileOutputStream("/myClientFiles");
BufferedOutputStream bufferOutStream = new BufferedOutputStream(fileOutStream);
bytesRead = inputStream.read(byteArray, 0, byteArray.length);
currentTotalNumberOfBytes = bytesRead;
do { //read till the end and store total in bytesRead and add it to currentTotalNumberOfBytes
bytesRead = inputStream.read(byteArray, currentTotalNumberOfBytes, (byteArray.length-currentTotalNumberOfBytes));
if(bytesRead >= 0) currentTotalNumberOfBytes += bytesRead;
}while(bytesRead > -1); // when bytesRead == -1, there's no more data left and we exit the loop
bufferOutStream.write(byteArray, 0 , currentTotalNumberOfBytes); //write the bytes to the file
bufferOutStream.flush();
bufferOutStream.close();
socket.close();
}
}
Server.java
ServerSocket serverSocket = new ServerSocket(2665);
Socket socket = serverSocket.accept();
System.out.println("Connected to: " + socket);
//File transferFile = new File("Allcrisis.doc"); //get local file
File[] transferFiles = new File("/myServerFiles").listFiles(); //array to store pathnames of files in myServerFiles folder
byte[] bytearray = new byte[(int)transferFiles.length];
for(File file: transferFiles){
//FileInputStream fileInputStream = new FileInputStream(transferFiles);
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream butterInputStream = new BufferedInputStream(fileInputStream);
butterInputStream.read(bytearray, 0, bytearray.length);
OutputStream outStream = socket.getOutputStream();
System.out.println("Sending...");
outStream.write(bytearray, 0, bytearray.length);
outStream.flush();
}
socket.close();
You have a folder /myClientFiles.
Your code contains
new FileOutputStream("/myClientFiles")
which attempts to open a FileOutputStream to write to that folder. You can't write to a folder.
You might want to pass new FileOutputStream the path to the file to write to.

avoiding garbage data while reading data using a byte buffer

I am trying to write a program to transfer a file between client and server using java tcp sockets I am using buffer size of 64K but The problem I am facing is that when when the tcp sometimes fail to send the whole 64K it sends the remaing part for example 32K in anther go
There for A garbage data of some Spaces or so is being taken by the buffer at reading side to make 64K complete and thus unnecessary data is making the file useless at receiving side.
Is there any solution to overcome this problem ???
I am using TCP protocol this code is using to send data to client
Server-side code
File transferFile = new File ("Document.txt");
byte [] bytearray = new byte [1024];
int byRead=0;
FileInputStream fin = new FileInputStream(transferFile);
BufferedInputStream bin = new BufferedInputStream(fin);
OutputStream os = socket.getOutputStream();
while(byRead>-1) {
byRead=bin.read(bytearray,0,bytearray.length);
os.write(bytearray,0,bytearray.length);
os.flush();
}
Client-side code
byte [] bytearray = new byte [1024];
InputStream is = socket.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\Users\\NetBeansProjects\\"+filename);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(bytearray,0,bytearray.length);
currentTot = bytesRead; System.out.println("Data is being read ...");
do {
bytesRead = is.read(bytearray, 0, (bytearray.length));
if(bytesRead == 0) continue;
if(bytesRead >= 0) currentTot += bytesRead;
bos.write(bytearray,0,bytearray.length);
} while(bytesRead > -1);
here I tried to skip the loop if the byte is empty by continue; statement but it is not
working.
bos.write(bytearray,0,bytearray.length);
This should be
bos.write(bytearray,0,bytesRead);
The region after 'bytesRead' in the buffer is undisturbed by the read. It isn't 'garbage'. It's just whatever was there before.
use CLIENT Side Code as below to get the total write bytes without garbage
int availableByte = socket.available();
if (availableByte > 0) {
byte[] buffer = new byte[availableByte];
int bytesRead = socketInputStream.read(buffer);
FileOutputStream fileOutputStream = new FileOutputStream(FilePath, true);
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
bufferedWriter.write(buffer.toString());
bufferedWriter.close();
}

Java TCP Server read file name

I want to create small client-server TCP file transfer program. And I have problem with one thing. When I send file from Client to Server, for example a txt file: omg.txt, I want the Server to read the incoming file name.
So - Client send omg.txt, Server says "New file recived: omg.txt". I tried to use BufferedReader (Server) and DataOutputStream (Client, because you have to write name of the file to send it) but it didnt work.
EDIT:
Client:
Socket sock = new Socket("localhost",13267);
System.out.println("Wait...");
Scanner input = new Scanner(System.in);
while(true){
// wysylanie
System.out.println("Filename");
String p = input.nextLine();
File myFile = new File (p);
boolean exists = (new File(p)).exists();
if (exists) {
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(sock.getOutputStream());
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Wait...");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done");
sock.close();
}
Server:
int filesize=6022386;
int bytesRead;
int current = 0;
ServerSocket servsock = new ServerSocket(13267);
Scanner input = new Scanner(System.in);
while (true) {
System.out.println("Wait...");
Socket sock = servsock.accept();
System.out.println("OK : " + sock);
// odbior pliku
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
bytesRead = is.read(mybytearray,0,mybytearray.length);
current = bytesRead;
do {
bytesRead =
is.read(mybytearray, current, (mybytearray.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
System.out.println("New filename");
String p = input.nextLine();
File plik = new File(p);
FileOutputStream fos = new FileOutputStream(plik);
BufferedOutputStream bos = new BufferedOutputStream(fos);
bos.write(mybytearray, 0 , current);
bos.flush();
System.out.println("File saved");
bos.close();
sock.close();
And I tried to do something like that:
Client addon:
DataOutputStream outToServer = new DataOutputStream(sock.getOutputStream());
sentence = input.nextLine();
outToServer.writeBytes(sentence);
Server addon:
BufferedReader inFromClient = new BufferedReader(new InputStreamReader(sock.getInputStream()));
clientSentence = inFromClient.readLine();
System.out.println(clientSentence);
...but unfortunetly I have "Wait.." all the time for Client
TCP just transfers raw data. If you want to send files with a filename, you may want to use a higher level protocol, such as FTP or TFTP.
If you really want to use plain TCP, you'll need to encode the filename in your message somehow. You could, for example, send the filename as the first line of the message, and then have the other end turn the rest of the message into a file with that name.
This may be helpful to you: http://www.adp-gmbh.ch/blog/2004/november/15.html

Categories

Resources