I am trying to write an application using Java that will allow me to transfer files between a server and a client that requests the file. I plan to do it using sockets. My algorithm is somewhat like this:
On Server:
Create the connection between client and server.
Once connected find the file u need to send to client.
Then send the size of file to client.
Then send file broken down in parts.
On Client
After connection is created, ask for the file.
Receive the file size, then accept data till u reach file size.
Stop.
Please correct me if i am wrong somewhere in the algorithm
This isn't really an "algorithm" question; you're designing a (simple) protocol. What you've described sounds reasonable, but it's too vague to implement. You need to be more specific. For example, some things you need to decide:
How does the receiving program know what filename it should save to? Should that be sent through the socket, or should it just ask the user?
How is the file size transmitted?
Is it a character string? If so, how is its length indicated? (With a null terminator? A newline?)
Is it a binary value? If so, how big? (32 bits or 64?) What endianness?
What does "broken down in parts" mean? If you're writing to a TCP socket, you don't need to worry about packet boundaries; TCP takes care of that.
Does the recipient send anything back, like a success or failure indication?
What happens when the whole file has been transmitted?
Should both ends assume that the connection must be closed?
Or can you send multiple files through a single connection? If so, how does the sender indicate that another file will follow?
Also, you're using the terms "client" and "server" backward. Typically the "client" is the machine that initiates a connection to a server, and the "server" is the machine that waits for connections from clients.
You can also add Acknowledgement from server once a particular part of the file is recieved,
similar to what we have in HTTP protocol , that would ensure proper delivery of the file has been received on the server.
Here is the method that I use, it uses the socket's input and output streams to send and receive the files, and when it's done, it will automatically restart the server and reconnect to it from the client.
Server Code:
package app.server;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Functions
{
private static ServerSocket server;
private static Socket socket;
public static void startServer(int port)
{
try
{
server = new ServerSocket(port);
socket = server.accept();
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
private static void restartServer()
{
new Thread()
{
#Override
public void run()
{
try
{
socket = server.accept();
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
public static void sendFile(String inputFilePath)
{
FileInputStream fis;
BufferedInputStream bis;
OutputStream os;
BufferedOutputStream bos;
try
{
File input = new File(inputFilePath);
fis = new FileInputStream(input);
bis = new BufferedInputStream(fis);
os = socket.getOutputStream();
bos = new BufferedOutputStream(os);
byte[] buffer = new byte[1024];
int data;
while(true)
{
data = bis.read(buffer);
if(data != -1)
{
bos.write(buffer, 0, 1024);
}
else
{
bis.close();
bos.close();
break;
}
}
}
catch (FileNotFoundException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
restartServer();
}
}
Client Code:
package app.client;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Functions
{
private static Socket socket;
private static String hostName;
private static int portNumber;
public static void connectToServer(String host, int port)
{
new Thread()
{
#Override
public void run()
{
try
{
hostName = host;
portNumber = port;
socket = new Socket(host, port);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
}.start();
}
private static void reconnectToServer()
{
try
{
socket = new Socket(hostName, portNumber);
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static void receiveFile(String outputFilePath)
{
InputStream is;
BufferedInputStream bis;
FileOutputStream fos;
BufferedOutputStream bos;
try
{
File output = new File(outputFilePath);
is = socket.getInputStream();
bis = new BufferedInputStream(is);
fos = new FileOutputStream(output);
bos = new BufferedOutputStream(fos);
byte[] buffer = new byte[1024];
int data;
while(true)
{
data = bis.read(buffer);
if(data != -1)
{
bos.write(buffer, 0, 1024);
}
else
{
bis.close();
bos.close();
break;
}
}
}
catch (IOException ex)
{
Logger.getLogger(Functions.class.getName()).log(Level.SEVERE, null, ex);
}
reconnectToServer();
}
}
This method works very well, I use it for my server and client file transfer program, all you need to do is enter the Server Host's IP address and choose a port number (I use 8888).
Related
i want to send a .txt file from the client to server and get it back in upper case.
But this code do nothing.can anyone tell what is wrong here..?
SERVER : getting file from client and sending it back in upper case to the client.
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Arrays;
public class Assignment4_Server {
public static void main(String[] args) throws IOException {
byte[] bytearray = new byte[4096];
try (ServerSocket ss = new ServerSocket(4444)) {
Socket s = ss.accept();
InputStream is = s.getInputStream();
OutputStream os = s.getOutputStream();
int count;
String data = null ;
while((count = is.read(bytearray))>0){
data = Arrays.toString(bytearray).toUpperCase();
byte[] bytearrayout = data.getBytes();
os.write(bytearrayout);
}
s.close();
}
}
}
CLIENT : sending text.txt file to the server and getting file back after converted in upper case.
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.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class Assignment4_client {
public static void main(String[] args) throws IOException {
File file = new File("test.txt");
byte[] bytearray = new byte[4096];
Socket sc = new Socket("localhost",4444);
//send file
int countS , countR;
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = sc.getOutputStream();
while((countS = bis.read(bytearray))>0){
os.write(bytearray);
}
//recieve file in uppercase from server
InputStream is = sc.getInputStream();
byte[] bytearray2 = new byte[4096];
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while((countR = is.read(bytearray2))>0){
bos.write(bytearray2);
}
}
}
Here is a code that should help you. But before reading it you should be aware of what is happening:
Your client is not sending a 'stop reading' information to the server (read the client code below). That's why the server is stuck in the while loop when it is trying to read the data sent by the client. That is probably why you have tried to send the data back directly to the client. Shut down the socket output from the client side to respect the Socket contract and correctly free the socket (see TCP/IP).
The solution given doesn't take in account that the server should stay up after it has done its duty. Then, the server will not be able to serve more than one client at a time. This server is offering a one time service, which is pointless. To overcome this issue you should put everything in a while loop and bind every new server process into a new thread (I let you do that, its quite a joy).
The server doesn't take in account the whole size of the data an it could possibly run into an out of memory error if the data is too heavy. You should find a way to avoid this problem in a real implementation.
Both program should catch the exception and log it somewhere so you could be aware of any errors.
Writing a server is not so simple. You should normally write some kind of protocol with headers and other stuff like that. To avoid that, use objects like ObjectOutputStream and ObjectInputStream but it has some limitation like constraining your server in the Java world.
CLIENT
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
public class Client {
public void send(File file)
{
Socket sc = null;
try
{
byte[] bytearray = new byte[4096];
sc = new Socket("localhost", 4444);
// 1. Read the file, send its content, close it.
int count;
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
OutputStream os = sc.getOutputStream();
while((count = bis.read(bytearray))>0)
{
os.write(bytearray);
}
fis.close();
sc.shutdownOutput();
// 2. Delete old file, receive data, write it to new File.
InputStream is = sc.getInputStream();
bytearray = new byte[4096];
// Eventually do what you want with the file: new one, append, etc.
file.delete();
file.createNewFile();
FileOutputStream fos = new FileOutputStream(file);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
count = 0;
while((count = is.read(bytearray)) > 0)
{
bos.write(bytearray, 0, count);
}
fos.close();
bos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if (sc != null)
{
try
{
sc.close();
} catch (IOException e) {}
}
}
}
}
SERVER
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
Server()
{
Socket s = null;
byte[] bytearray = new byte[4096];
try (ServerSocket ss = new ServerSocket(4444))
{
s = ss.accept();
InputStream is = s.getInputStream();
// 1. Recieve data and put it to UpperCase.
String data = "";
int count;
while((count = is.read(bytearray)) > 0)
{
data += new String(bytearray, 0, count);
}
data = data.toUpperCase();
System.out.println(data);
// 2. Send back data.
OutputStream os = s.getOutputStream();
os.write(data.getBytes());
os.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
TEST PROGRAM
This one should help you to test your both programs in the same project in an IDE.
import java.io.File;
public class Test
{
public static void main(String[] args)
{
Client c = new Client();
(new Thread()
{
public void run()
{
Server s = new Server();
}
}).start();
c.send(new File("test.txt"));
}
}
What is wrong here is two simple things.
The server is reading until end of stream, on a socket that must be used for the reply. The client therefore cannot close it after sending the request to provide the EOS, so it must shutdown the socket for output after sending the request.
Your copy loops are wrong. The general form is:
while ((count = in.read(buffer)) > 0)
{
out.write(buffer, 0, count);
}
You are ignoring the read count when writing, so you will write junk at end of stream, or any other time that read() doesn't fill buffer, which can be any time at all.
I am new to java and network programming for the most part. I want to write a program that automatically backs up my texts to my computer whenever my phone connects to my home wifi.
I am working on creating java classes that will handle sending data over the network. Using some questions found here, I came up with this implementation but I have some questions regarding some of the methods used in what I learned from.
Two Questions Regarding this code
I totally used a question from SO for the send methods in my client. The sendText uses a new thread, but the sendFile doesn't. Any particular reason why?
2. At which point in the code does the server actually know when there has been a message sent to the port? Is it at the method accept() call or is it when the BufferStream readLine() is checked? Does accept just grab data and throw it into the buffer? null implying the data grabbed was not a signal sent from a client?
Does the accept() method block execution of the code until a connection attempt is made from a client?
Thanks!
KServ
//Used to launch the server
public class KServ {
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java KServ <port number>");
System.exit(1);
}
int port = Integer.parseInt(args[0]);
KServer server = new KServer(port);
while (true) { //added this to keep the server polling for new data
server.run();
}
}
}
KServer
//Server class. Should handle data incoming
import java.net.*;
import java.io.*;
public class KServer {
private int port;
public KServer(int PORT) {
port = PORT;
}
public void run() {
try (
ServerSocket sSocket = new ServerSocket(port);
Socket cSocket = sSocket.accept();
PrintWriter out = new PrintWriter(cSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(cSocket.getInputStream()));
) {
String input;
while ((input = in.readLine()) != null) {
System.out.println(input);
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port " + port + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
Client
//launches KClient object and uses it to send input from console to the server
import java.util.Scanner;
public class Client {
public static void main(String[] args) {
if (args.length != 2) {
System.err.println("Usage: java Client <ip number> <port number>");
System.exit(1);
}
String ip = args[0];
int port = Integer.parseInt(args[1]);
KClient client = new KClient(ip,port);
String msg;
Scanner inStream = new Scanner(System.in);
while((msg = inStream.nextLine()).length() > 0) {
client.sendText(msg);
}
}
}
KClient
//Will be used to establish connection with server and send data from phone
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
public class KClient {
private String server;
private int port;
public KClient(String Server,int Port) {
server = Server;
port = Port;
}
public void sendFile(String fileName) {
File file = new File(fileName);
FileInputStream fileInputStream;
BufferedInputStream bufferedInputStream;
OutputStream outputStream;
try {
client = new Socket(server,port);
byte[] bytes = new byte[(int) file.length()];
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(fileInputStream);
bufferedInputStream.read(bytes, 0, bytes.length);
outputStream = client.getOutputStream();
outputStream.write(bytes,0,bytes.length);
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private Socket client;
private OutputStreamWriter outputStreamWriter;
public void sendText(String msg) {
System.out.println("Send Message!");
new Thread(new Runnable() {
#Override
public void run() {
try {
client = new Socket(server,port);
outputStreamWriter = new OutputStreamWriter(client.getOutputStream(), "ISO-8859-1");
outputStreamWriter.write(msg);
outputStreamWriter.flush();
outputStreamWriter.close();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
BufferedReader inStream;
public boolean Shake() {
try {
client = new Socket(server,port);
inStream = new BufferedReader(new InputStreamReader(client.getInputStream()));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
}
I totally used a question from SO for the send methods in my client. The sendText uses a new thread, but the sendFile doesn't. Any particular reason why?
Unanswerable. Ask the author. Both sends can block. As the file is presumably longer than the text, it would have made more sense to do it the other way round.
2. At which point in the code does the server actually know when there has been a message sent to the port? Is it at the method accept() call
No.
or is it when the BufferStream readLine() is checked?
Yes.
Does accept just grab data and throw it into the buffer?
No. It grabs a connection and returns it as a socket. Nothing to do with data whatsoever.
null implying the data grabbed was not a signal sent from a client?
You seem to be actually asking about BufferedReader.readLine() here, not ServerSocket.accept(), which doesn't return null. readLine() returns null when there is no pending data to be read and the peer has closed the connection.
Does the accept() method block execution of the code until a connection attempt is made from a client?
More or less. It blocks until there is a complete connection waiting to be accepted, which isn't quite the same thing, as there is a queue.
I will add that you have copied, or written, some truly terrible code here. There are much better examples.
I'm working on a project and i want to comunicate with a device. I made a socket connection with the device, the connection works but the device is sending me the message: 0xd7d0 and i have to write that message back. It's a keep alive message. I'm haveing trouble reading and sending back that message.
here's the code i've writen so far:
package Server;
import java.io.IOException;
import java.net.ServerSocket;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Server {
public static ServerSocket serverSocket;
public static void main (String [] args) {
try {
serverSocket = new ServerSocket(1234);
while (true) {
ServerThread serverThread = new ServerThread(serverSocket.accept());
serverThread.start();
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.util.logging.Level;
import java.util.logging.Logger;
public class ServerThread extends Thread {
public Socket socket;
public BufferedReader in;
public PrintWriter out;
public ByteBuffer buf;
int count;
public ServerThread (Socket socket) {
try {
this.socket = socket;
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
#Override
public void run() {
while (true) {
try {
count = in.read();
buf = ByteBuffer.allocate(100);
buf.put((byte) count);
buf.flip();
out.println(buf);
String line = in.readLine();
System.out.println(line);
} catch (IOException ex) {
Logger.getLogger(ServerThread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Can anyone tell me what i am doing wrong?
This
while (true) {
ServerThread serverThread = new ServerThread(serverSocket.accept());
serverThread.start();
}
doesn't look right. You're looping and creating a new thread repeatedly (which will consume resources and create an enormous number of threads). You should simply create that thread once. If your program is doing nothing else then a new thread may be superfluous.
Your mistake is that you mix different styles of network data exchange. First, what format are messages in? Are they characters in some encoding, or some binary data? In the first case, you should not use Buffer to read message in, but read and write using in and out character streams you created already. In the second case, you have 2 options: read and write with socket and byte streams, or with channels from java.nio.channels and Buffers. To write back a message in a buffer, you can use
buf.flip();
buffer.position(buffer.limit());
I have Developed an Stand alone application (.jar) which is working on Linux environment, I want to Keep this Application on a server(Linux) and want to access through other systems.
Please suggest if this is Possible.
Have you considered Java Webstart ? It'll allow clients to download your application from a webserver and run it locally.
It's traditionally used with GUI (Swing etc.) apps, but I've used it to run daemon and server processes locally.
It'll handle application updates automatically so your clients will only download a version if they'll need it. Otherwise they'll access their locally cached version.
Linux system implements the Berkeley socket API, so yes, you can open communication for the other machines.
For this, you can use package java.net. For socket connection we can use: Socket, ServerSocket, and SocketAddress.
Socket is used for the client, ServerSocket is used to created a socket server, and SocketAddress is used to provide information that will be used as a target socket.
As the illustration, please find the projects below:
First Project SocketServerApp.java - build this and then run java -jar SocketServerApp.jar
package socketserverapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class SocketServerApp {
public static void main(String[] args) throws IOException {
//we defines all the variables we need
ServerSocket server = null;
Socket client = null;
byte[] receivedBuff = new byte[64];
int receivedMsgSize;
try
{
//activate port 8881 as our socket server
server = new ServerSocket(8881);
System.out.println("Server started");
//receiving connection from client
client = server.accept();
System.out.println("Client connected");
}
catch (IOException e)
{
System.out.println(e.getMessage());
System.exit(-1);
}
//prepare data stream
InputStream in = client.getInputStream();
OutputStream out = client.getOutputStream();
//greet user if there is a client connection
String data;
data = "Hello from the Server!";
out.write(data.getBytes());
//accepting data from client and display it in the console.
java.util.Arrays.fill(receivedBuff, (byte)0);
while (true) {
receivedMsgSize = in.read(receivedBuff);
data = new String(receivedBuff);
//if client type "exit", then exit loop and close everything
if (data.trim().equals("exit"))
{
out.write(data.getBytes());
break;
}
java.util.Arrays.fill(receivedBuff, (byte)0);
System.out.println ("Client: " + data);
}
//close all resources before exiting
out.close();
in.close();
client.close();
server.close();
}
}
Second project is the SocketClientApp.java - build this and then run java -jar SocketClientApp.jar
package socketclientapp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class SocketClientApp {
public static void main(String[] args) throws IOException {
Socket client = null;
InputStream in = null;
OutputStream out = null;
byte[] receivedMsg = new byte[64];
try {
client = new Socket("localhost", 8881);
in = client.getInputStream();
out = client.getOutputStream();
} catch (UnknownHostException e) {
System.err.println(e.getMessage());
System.exit(1);
} catch (IOException e) {
System.err.println(e.getMessage());
System.exit(1);
}
String fromServer;
String fromUser;
in.read(receivedMsg);
fromServer = new String(receivedMsg);
System.out.println("Server: " + fromServer);
fromUser = "Hello from Client";
System.out.println("Sent to server: " + fromUser);
out.write(fromUser.getBytes());
fromUser = "exit";
out.write(fromUser.getBytes());
System.out.println("Sent to server: " + fromUser);
out.close();
in.close();
client.close();
}
}
Short to say this is a TCP/IP Communication. This type of communication method is very usual in an enterprise that has many kinds of softwares.
Hope that helps.
I have created a basic Client Server that will send image files in a specified directory over a network. The code worked last week but I came back to it today and it seems that I am only getting one file on the server side, even though the client prints out that it has sent all the image files in the directory.
It may be something in the client code but I think it is something on the server side.
Any help is greatly appreciated and if you have a more efficient solution, I am happy to change my code as necessary. My code is below:
ImageServer
package com.encima.network.server;
import java.io.*;
import java.net.*;
public class ImageServer{
ServerSocket ss;
Socket s;
ObjectOutputStream oos;
int port = 4440;
public ImageServer() throws IOException {
try {
ss = new ServerSocket(port);
System.out.println("Server started on Port: " + port);
} catch(IOException e) {
System.out.println("Serevr: Port-" + port + " not available, exiting.");
System.exit(0);
}
System.out.println("Server: Waiting for Client Connection...");
while(true) {
try {
s = ss.accept();
new ImageHandler(s);
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) throws IOException {
ImageServer is = new ImageServer();
}
}
ImageHandler
package com.encima.network.server;
import java.awt.image.BufferedImage;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.net.Socket;
import javax.imageio.ImageIO;
public class ImageHandler implements Runnable {
Socket s;
int count = 0;
public ImageHandler(Socket socket) {
s = socket;
Thread t = new Thread(this);
t.start();
}
#Override
public void run() {
try {
ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
FileOutputStream fos = new FileOutputStream("image" + System.nanoTime() + ".jpg");
count++;
//BufferedImage in = ImageIO.read(ois);
//ImageIO.write(in, "jpg", fos);
int ch = 0;
while(true) {
ch = ois.read();
if(ch == -1) {
break;
}
fos.write(ch);
}
fos.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Finally, the ImageClient
package com.encima.network.client;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.net.Socket;
import javax.imageio.ImageIO;
import com.encima.network.ImageFilter;
public class ImageClient {
Socket s;
String ip = "localhost";
int port = 4440;
ObjectOutputStream oos;
public ImageClient(File[] files) throws IOException, ClassNotFoundException, InterruptedException {
try {
s = new Socket(ip, port);
System.out.println("Client connected to Server via " + ip + " on port 80");
} catch (Exception e) {
System.out.println("Client: Cannot find Host: " + ip + ". Exiting.");
System.exit(0);
}
oos = new ObjectOutputStream(s.getOutputStream());
for(File f: files) {
sendFile(f);
}
oos.close();
//System.out.println("Written Image " + i + " of " + files.length);
}
public static void main(String[] args) throws IOException, ClassNotFoundException, InterruptedException {
File dir = new File("/Users/christophergwilliams/Dropbox/PhD/Projects/PhD/Year 1/GSN/images");
File[] files = dir.listFiles(new ImageFilter());
ImageClient ic = new ImageClient(files);
}
public void sendFile(File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
//BufferedImage b = ImageIO.read(file);
//ImageIO.write(b, "jpg", oos);
int ch = 0;
while(true) {
ch = fis.read();
if(ch == -1) {
break;
}
oos.write(ch);
}
oos.flush();
System.out.println("Image Sent");
}
}
I am aware that it is a lot of code to read through but I do appreciate any help I can get on this!
I may be wrong but, for the sake of efficiency and network traffic, would it be beneficial to send the images as a zip from the client to the server?
Why are you using ObjectInputStream at all? You're not reading or writing any serialized objects - just raw binary data. Use whatever InputStream is provided, and read from that.
Anyway, that's not the big problem. The big problem is that you're just writing several files to one stream, with no indication of where one file is meant to finish and the next one is meant to start. How were you expecting to split the multiple files up? Options:
Use a delimiter between files (very ugly - you'd have to potentially escape any data which looked like the delimiter as you went along)
Prefix each file with its length
Send each file on a different connection
(You're also reading and writing a single byte at a time. Use the overloads of read/write which accept byte arrays.)