I have been fixing my server many times and now i'm stuck ones again.
So I have been trying to send pictures through my clientGUI to a server, So the person can see the file im sending. I dont really know how to explain this. but however. Im just trying to send a file so the other client can accept it and save it. BUT as fast as I press the button picture (It should automatic send a picture to a desktop that I have placed) it does work,
Connection is accepted; localhost/127.0.0.1 - 1500
Sending C:/Users/Barry/Desktop/Ceo/Cao6.jpg(15306 bytes)
Server has closed the connection
but i'm not getting anything in the desktop and in my ServerGUI, I can see that it says :
Exception reading Streams: java.io.StreamCorruptedException: invalid type code: FF
which I have no idea how to fix it and I need some ideas how I can fix this.
Sendpic.java
public void SendPic() throws IOException {
JFileChooser chooser = new JFileChooser();
String FILESEND = "C:/Users/Barry/Desktop/Ceo/Cao6.jpg";
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
try {
// send file
File myFile = new File (FILESEND);
byte [] mybytearray = new byte [(int)myFile.length()];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
os = socket.getOutputStream();
System.out.println("Sending " + FILESEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
} catch (IOException e) {
e.printStackTrace();
}
}
getPic.Java
final static int FILE_SIZE = 6022386;
public void getPic() throws IOException {
JFileChooser chooser = new JFileChooser();
String FILETORECEIVED = "C:/Users/Barry/Desktop/";
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = socket.getInputStream();
fos = new FileOutputStream(FILETORECEIVED);
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 " + FILE_SIZE
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
}
}
ActionPerformed`
public void actionPerformed(ActionEvent e) {
Object button = e.getSource();
if (button == btnPicture) {
try {
controller.SendPic();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return;
}`
Related
How do I make the files in the server appear in a list and appear a number behind it and press its number and download by inserting its number?
The point is trading files with my self that point I can but listing the files that I have in the directory I cant, I can already download files (thats the main point)
int porto = 21;
String IP = "x.x.x.x";
public Client() {
String destinyfile = "directory";
try {
Socket MyClient = new Socket(IP, porto);
DataInputStream input = new DataInputStream(MyClient.getInputStream());
DataOutputStream output = new DataOutputStream(MyClient.getOutputStream());
System.out.println(input.readUTF());
String arquivo = JOptionPane.showInputDialog("Insert the name of the file");
output.writeUTF(arquivo);
ObjectInputStream in = new ObjectInputStream(MyClient.getInputStream());
String fileName = in.readUTF();
if(fileName != null){
long size = in.readLong();
System.out.println("Processing the file: " + fileName + " - "+ size + " bytes.");
File file = new File(destinyfile);
if(file.exists() == false){
file.mkdir();
}
FileOutputStream fos = new FileOutputStream(caminhoDestino + fileName);
byte[] buf = new byte[4096];
while (true) {
int len = in.read(buf);
if (len == -1)
break;
fos.write(buf, 0, len);
}
fos.flush();
fos.close();
}
System.out.println(input.readUTF());
MyClient.close();
} catch (Exception e) {
Server
int port = 21;
public Servidor() {
try {
ServerSocket ss = new ServerSocket(port);
String caminho = "directory";
while (true) {
System.out.println("Waiting user.");
Socket socket = ss.accept();
DataInputStream input = new DataInputStream(socket.getInputStream());
DataOutputStream output = new DataOutputStream(socket.getOutputStream());
output.writeUTF("Welcome");
String arq = input.readUTF();
System.out.println("File: " + arq);
File file = new File(caminho + arq);
if(file.exists()){
ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
System.out.println("Transfering file: " + file.getName());
out.writeUTF(file.getName());
out.writeLong(file.length());
FileInputStream filein = new FileInputStream(file);
byte[] buf = new byte[4096];
while (true) {
int len = filein.read(buf);
if (len == -1)
break;
out.write(buf, 0, len);
}
out.close();
output.writeUTF("File Sent:");
}else{
output.writeUTF("File doesnt exist!");
}
ss.close();
}
} catch (Exception e) {
If you create a File object for the parent directory of the files you want to list, you can call that object's listFiles() to get an array of File objects in that directory.
E.g.
File parent = new File("/data/folder/");
for (File child : parent.listFiles()) {
System.out.println(child.getName());
}
I am getting error when i am trying to decompressing the files coming from server,but i am getting error of invalid bit length in while loop.Is there any problem with code or encoding.
byte[] buffer = new byte[1024];
FileInputStream fileInput = null;
FileOutputStream fileOutputStream = null;
GZIPInputStream gzipInputStream = null;
System.out.println(source_compressed_filepath);
System.out.println(destinaton_decompressed_filepath);
try {
fileInput = new FileInputStream(source_compressed_filepath);
gzipInputStream = new GZIPInputStream(fileInput);
fileOutputStream = new FileOutputStream(destinaton_decompressed_filepath);
int len;
while ((len = gzipInputStream.read(buffer)) >=0) {
fileOutputStream.write(buffer, 0, len);
}
System.out.println("The file" + source_compressed_filepath + " was DeCompressed successfully!"
+ destinaton_decompressed_filepath);
}catch (IOException ex) {
System.out.println(" error in file decompression " + source_compressed_filepath);
} finally {
// close resources
try {
fileOutputStream.close();
gzipInputStream.close();
} catch (IOException e) {
}
}
I have two projects; one for my server and one for my client, I am able to send images to the server with ease. But I am wondering how would you be able to download that image you just sent to the server back to the client when I press the download button I have created on my client GUI? My code is written in java.
Many Thanks
This is my serverhandler
String fileName;
fileName = "RecievedImageoutreach1.jpg";
DataOutputStream dout = new DataOutputStream(sock.getOutputStream());
//Coding for image transfer
int flag=0,i;
String extn="";
for(i=0; i<fileName.length(); i++)
{
if(fileName.charAt(i)=='.' || flag==1)
{
flag=1;
extn += fileName.charAt(i);
}
}
if(extn.equals(".jpg") || extn.equals(".gif"))
{
try{
File file = new File(fileName);
FileInputStream fin = new FileInputStream(file);
dout.writeUTF(fileName);
byte[] readData = new byte[1024];
while((i = fin.read(readData)) != -1)
{
dout.write(readData, 0, i);
}
//ta.appendText("\nImage Has Been Sent");
dout.flush();
fin.close();
}catch(IOException ex)
{System.out.println("Image ::"+ex);}
}
}
And this is my client
public void download() throws IOException {
// Get input from the server
DataInputStream dis = new DataInputStream (sock.getInputStream());
String str,extn = "";
str = dis.readUTF();
int flag=0,i;
for(i=0;i<str.length();i++)
{
if(str.charAt(i)=='.' || flag==1)
{
flag=1;
extn+=str.charAt(i);
}
}
//**********************reading image*********************************//
if(extn.equals(".jpg") || extn.equals(".gif"))
{
File file = new File("Downloaded"+str);
FileOutputStream fout = new FileOutputStream(file);
//receive and save image from client
byte[] readData = new byte[1024];
while((i = dis.read(readData)) != -1)
{
fout.write(readData, 0, i);
if(flag==1)
{
ta.append("Image Has Been Downloaded");
flag=0;
}
}
fout.flush();
fout.close();
}
}
But when run nothing occurs? i have linked the client method to run when a button is clicked.
I would do something like this:
//Server Handler
File file = new File(fileName);
FileInputStream fin = new FileInputStream(file);
// dout.writeUTF(fileName);
byte[] readData = new byte[1024];
fin.read(readData);
fin.close();
dout.write(readData, 0, readData.length);
dout.flush();
/* while((i = fin.read(readData)) != -1)
{
dout.write(readData, 0, i);
}*/
//ta.appendText("\nImage Has Been Sent");
dout.flush();
fin.close();
}catch(IOException ex)
{System.out.println("Image ::"+ex);}
}
//Receiving image
if(extn.equals(".jpg") || extn.equals(".gif"))
{
//give path to new file
File file = new File(".//Downloaded"+str);
FileOutputStream fout = new FileOutputStream(file);
//receive and save image from client
byte[] readData = new byte[1024];
int offset =0;
while((i = dis.read(readData,0,readData.length-offset)) != -1){
offset += i;
}
fout.write(readData, 0, readData.length);
if(flag==1)
{
ta.append("Image Has Been Downloaded");
flag=0;
}
fout.flush();
fout.close();
}
}
Assuming that you would have to provide file name and then press download button. So on server side convert the image into byte stream and write over the connection socket. On client side recieve bytes into buffer and then create FileOutputStream providing the directory for output. Write the recieved bytes onto the file using the outputstream created.
I am trying to send a file from client to server. Below is the code i have tried. But at times, there is a packet loss during the transfer. I am not sure where i am wrong.
SERVER SIDE CODE:
public static void ReadAndWrite(byte[] aByte, Socket clientSocket,
InputStream inputStream, String fileOutput)
throws FileNotFoundException, IOException {
int bytesRead;
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try
{
fileOutputStream = new FileOutputStream( fileOutput );
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
bytesRead = inputStream.read(aByte, 0, aByte.length);
System.out.println("The length is "+bytesRead);
int count = 0;
do {
count++;
byteArrayOutputStream.write(aByte);
bytesRead = inputStream.read(aByte);
} while (bytesRead != -1);
System.out.println("The count is "+count);
System.out.println("The length is "+byteArrayOutputStream.size());
bufferedOutputStream.write(byteArrayOutputStream.toByteArray());
bufferedOutputStream.flush();
bufferedOutputStream.close();
clientSocket.close();
}
catch(Exception ex)
{
Logger.writeLog(ex,Listen.class.getName(), LogType.EXCEPTION);
throw ex;
}
CLIENT SIDE CODE:
public void readByteArrayAndWriteToClientSocket(
Socket connectionSocket, BufferedOutputStream outToClient, String fileToSend ) throws Exception
{
try{
if (outToClient != null)
{
File myFile = new File(fileToSend);
System.out.println(myFile.length());
byte[] byteArray = new byte[(int) myFile.length()];
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(myFile);
} catch (IOException ex) {
Logger.writeLog(ex, FileUtility.class.getName(), LogType.EXCEPTION);
throw ex;
}
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
try {
bufferedInputStream.read(byteArray, 0, byteArray.length);
outToClient.write(byteArray, 0, byteArray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
return;
} catch (IOException ex) {
Logger.writeLog(ex, FileUtility.class.getName(), LogType.EXCEPTION);
throw ex;
}
}
}catch (Exception e) {
Logger.writeLog(e, getClass().getName(), LogType.EXCEPTION);
throw e;
}
}
There is no 'packet loss', just bugs in your code.
The canonical way to copy a stream in Java is as follows:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
If you know the number of bytes in advance and the sender must keep the connection open after the transfer, it becomes:
while (total < expected && (count = in.read(buffer, 0, expected-total > buffer.length ? buffer.length : (int)(expected-total))) > 0)
{
out.write(buffer, 0, count);
total += count;
}
Forget all the ByteArrayInput/OutputStreams and the extra copies. Just read from the file and send to the socket, or read from the socket and write to the file.
The sockets read method will return when its has obtained all the bytes you asked for, OR, when it stops receiving data from the network.
As transmission is often interrupted in any real network you need to keep issuing read calls until you have the number of bytes you want.
You need code something like this:
char [] buffer = new char[1024];
int expect = 1000;
int sofar = 0;
int chars_read;
try
{
while((chars_read = from_server.read(buffer[sofar])) != -1)
{
sofar = sofar + chars_read;
if (sofar >= expected) break;
}
}
catch(IOException e)
{
to_user.println(e);
}
I am trying to develop a very simple client / server where the client converts a file to bytes, sends it to the server, and then converts the bytes back in to a file.
Currently the program just creates an empty file. I'm not a fantastic Java developer so any help much appreciated.
This is the server part that receives what the client sends.
ServerSocket serverSocket = null;
serverSocket = new ServerSocket(4444);
Socket socket = null;
socket = serverSocket.accept();
DataOutputStream out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
DataInputStream in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
byte[] bytes = new byte[1024];
in.read(bytes);
System.out.println(bytes);
FileOutputStream fos = new FileOutputStream("C:\\test2.xml");
fos.write(bytes);
And here is the client part
Socket socket = null;
DataOutputStream out = null;
DataInputStream in = null;
String host = "127.0.0.1";
socket = new Socket(host, 4444);
out = new DataOutputStream(new BufferedOutputStream(socket.getOutputStream()));
in = new DataInputStream(new BufferedInputStream(socket.getInputStream()));
File file = new File("C:\\test.xml");
//InputStream is = new FileInputStream(file);
// Get the size of the file
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large.");
}
byte[] bytes = new byte[(int) length];
//out.write(bytes);
System.out.println(bytes);
out.close();
in.close();
socket.close();
The correct way to copy a stream in Java is as follows:
int count;
byte[] buffer = new byte[8192]; // or 4096, or more
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
Wish I had a dollar for every time I've posted that in a forum.
Thanks for the help. I've managed to get it working now so thought I would post so that the others can use to help them.
Server:
public class Server {
public static void main(String[] args) throws IOException {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(4444);
} catch (IOException ex) {
System.out.println("Can't setup server on this port number. ");
}
Socket socket = null;
InputStream in = null;
OutputStream out = null;
try {
socket = serverSocket.accept();
} catch (IOException ex) {
System.out.println("Can't accept client connection. ");
}
try {
in = socket.getInputStream();
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
out = new FileOutputStream("M:\\test2.xml");
} catch (FileNotFoundException ex) {
System.out.println("File not found. ");
}
byte[] bytes = new byte[16*1024];
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
serverSocket.close();
}
}
and the Client:
public class Client {
public static void main(String[] args) throws IOException {
Socket socket = null;
String host = "127.0.0.1";
socket = new Socket(host, 4444);
File file = new File("M:\\test.xml");
// Get the size of the file
long length = file.length();
byte[] bytes = new byte[16 * 1024];
InputStream in = new FileInputStream(file);
OutputStream out = socket.getOutputStream();
int count;
while ((count = in.read(bytes)) > 0) {
out.write(bytes, 0, count);
}
out.close();
in.close();
socket.close();
}
}
Here is the server
Open a stream to the file and send it overnetwork
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SimpleFileServer {
public final static int SOCKET_PORT = 5501;
public final static String FILE_TO_SEND = "file.txt";
public static void main (String [] args ) throws IOException {
FileInputStream fis = null;
BufferedInputStream bis = null;
OutputStream os = null;
ServerSocket servsock = null;
Socket sock = null;
try {
servsock = new ServerSocket(SOCKET_PORT);
while (true) {
System.out.println("Waiting...");
try {
sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
// send file
File myFile = new File (FILE_TO_SEND);
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 " + FILE_TO_SEND + "(" + mybytearray.length + " bytes)");
os.write(mybytearray,0,mybytearray.length);
os.flush();
System.out.println("Done.");
} catch (IOException ex) {
System.out.println(ex.getMessage()+": An Inbound Connection Was Not Resolved");
}
}finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null)
servsock.close();
}
}
}
Here is the client
Recive the file being sent overnetwork
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 5501;
public final static String SERVER = "127.0.0.1";
public final static String
FILE_TO_RECEIVED = "file-rec.txt";
public final static int FILE_SIZE = Integer.MAX_VALUE;
public static void main (String [] args ) throws IOException {
int bytesRead;
int current = 0;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
Socket sock = null;
try {
sock = new Socket(SERVER, SOCKET_PORT);
System.out.println("Connecting...");
// receive file
byte [] mybytearray = new byte [FILE_SIZE];
InputStream is = sock.getInputStream();
fos = new FileOutputStream(FILE_TO_RECEIVED);
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 " + FILE_TO_RECEIVED
+ " downloaded (" + current + " bytes read)");
}
finally {
if (fos != null) fos.close();
if (bos != null) bos.close();
if (sock != null) sock.close();
}
}
}
To avoid the limitation of the file size , which can cause the Exception java.lang.OutOfMemoryError to be thrown when creating an array of the file size byte[] bytes = new byte[(int) length];, instead we could do
byte[] bytearray = new byte[1024*16];
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
OutputStream output= socket.getOututStream();
BufferedInputStream bis = new BufferedInputStream(fis);
int readLength = -1;
while ((readLength = bis.read(bytearray)) > 0) {
output.write(bytearray, 0, readLength);
}
bis.close();
output.close();
}
catch(Exception ex ){
ex.printStackTrace();
} //Excuse the poor exception handling...
Rookie, if you want to write a file to server by socket, how about using fileoutputstream instead of dataoutputstream? dataoutputstream is more fit for protocol-level read-write. it is not very reasonable for your code in bytes reading and writing. loop to read and write is necessary in java io. and also, you use a buffer way. flush is necessary. here is a code sample: http://www.rgagnon.com/javadetails/java-0542.html
Adding up on EJP's answer; use this for more fluidity.
Make sure you don't put his code inside a bigger try catch with more code between the .read and the catch block, it may return an exception and jump all the way to the outer catch block, safest bet is to place EJPS's while loop inside a try catch, and then continue the code after it, like:
int count;
byte[] bytes = new byte[4096];
try {
while ((count = is.read(bytes)) > 0) {
System.out.println(count);
bos.write(bytes, 0, count);
}
} catch ( Exception e )
{
//It will land here....
}
// Then continue from here
EDIT: ^This happened to me cuz I didn't realize you need to put socket.shutDownOutput() if it's a client-to-server stream!
Hope this post solves any of your issues