I am writing a simple web server program for class that sends files to the web browser on request. I have written as much as I could. The difficulty is getting the data written to the OutputStream. I don't know what I am missing. I couldn't get the simple request to show up on the web browser.
I wrote it to the "name" OutputStream but when I reload the tab in the browser with the URL: "http://localhost:50505/path/file.txt" or any other like that "localhost:50505" it doesn't show up what I wrote to the OutputStream "name". It is supposed to show that.
package lab11;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketImpl;
import java.util.Scanner;
import java.io.OutputStream;
import java.io.PrintWriter;
public class main {
private static final int LISTENING_PORT = 50505;
public static void main(String[] args) {
ServerSocket serverSocket;
try {
serverSocket = new ServerSocket(LISTENING_PORT);
}
catch (Exception e) {
System.out.println("Failed to create listening socket.");
return;
}
System.out.println("Listening on port " + LISTENING_PORT);
try {
while (true) {
Socket connection = serverSocket.accept();
System.out.println("\nConnection from "
+ connection.getRemoteSocketAddress());
handleConnection(connection);
}
}
catch (Exception e) {
System.out.println("Server socket shut down unexpectedly!");
System.out.println("Error: " + e);
System.out.println("Exiting.");
}
}
public static void handleConnection(Socket sok) {
try {
// Scanner in = new Scanner(sok.getInputStream());
InputStream one = sok.getInputStream();
InputStreamReader isr = new InputStreamReader(one);
BufferedReader br = new BufferedReader(isr);
String rootDirectory = "/files";
String pathToFile;
// File file = new File(rootDirectory + pathToFile);
StringBuilder request = new StringBuilder();
String line;
line = br.readLine();
while (!line.isEmpty()) {
request.append(line + "\r\n");
line = br.readLine();
}
// System.out.print(request);
String[] splitline = request.toString().split("\n");
String get = null;
String file = null;
for (String i : splitline) {
if (i.contains("GET")) {
get = i;
String[] splitget = get.split(" ");
file = splitget[1];
}
}
}
OutputStream name = sok.getOutputStream();
Boolean doesexist = thefile.exists();
if (doesexist.equals(true)) {
PrintWriter response = new PrintWriter(System.out);
response.write("HTTP/1.1 200 OK\r\n");
response.write("Connection: close\r\n");
response.write("Content-Length: " + thefile.length() + "\r\n");
response.flush();
response.close();
sendFile(thefile, name);
} else {
System.out.print(thefile.exists() + "\n" + thefile.isDirectory() + "\n" + thefile.canRead());
}
}
catch (Exception e) {
System.out.println("Error while communicating with client: " + e);
}
finally { // make SURE connection is closed before returning!
try {
sok.close();
}
catch (Exception e) {
}
System.out.println("Connection closed.");
}
}
private static void sendFile(File file, OutputStream socketOut) throws
IOException {
InputStream in = new BufferedInputStream(new FileInputStream(file));
OutputStream out = new BufferedOutputStream(socketOut);
while (true) {
int x = in.read(); // read one byte from file
if (x < 0)
break; // end of file reached
out.write(x); // write the byte to the socket
}
out.flush();
}
}
So, I don't know what I really did wrong.
When I load the browser with localhost:50505 it just says can't connect or localhost refused to connect.
You are writing the HTTP response in System.out. You should write it in name, after the headers, in the body of the response. You probably want to describe it with a Content-Type header to make the receiver correctly show the file.
Related
Its driving me nuts trying days to grind this problem.
I am writing a java server to work with an android application. They communicate text string and xml.
Currently simple socket communication seems fine, however it breaks down when I tried to use transformer instead of simple println.
Server code as below
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.Charset;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
public class javamultithreadedserver implements Runnable {
Socket csocket;
static int listenport = 6021;
public static final String endOfCom = "endofcom";
String connectionname;
public javamultithreadedserver(Socket csocket, String connectionname) {
this.csocket = csocket;
this.connectionname = connectionname;
}
public static void main(String[] args) throws Exception {
int listentoport = 0;
//System.out.println(args.length);
if (args.length == 1){
listentoport = Integer.parseInt(args[0]);
} else{
listentoport = listenport;
}
ServerSocket ssock = new ServerSocket(listentoport);
System.out.println("Listening at port " + listentoport);
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected. from: " + sock.getInetAddress().getHostAddress() + " " + sock.getInetAddress().getHostName() + " port: " + sock.getPort() + " " + sock.getInetAddress().getCanonicalHostName());
new Thread(new javamultithreadedserver(sock, sock.getInetAddress().getHostAddress() + " " + sock.getInetAddress().getHostName() + " " + sock.getInetAddress().getCanonicalHostName())).start();
}
}
#Override
public void run() {
try {
PrintWriter out = new PrintWriter(csocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(csocket.getInputStream()));
PrintStream pstream = new PrintStream (csocket.getOutputStream(), true);
String inputLine, outputLine;
System.out.println(connectionname + ": listening for query information.");
while ((inputLine = in.readLine()) != null) {
System.out.println(connectionname + ": " + inputLine);
//out.write("received something");
DBQuery q = new DBQuery(inputLine + DBQuery.regexsplit + "connectionname" + DBQuery.regexsplit + connectionname);
DOMSource dmsource = q.returns();
***//StreamResult consoleResult = new StreamResult(System.out); //debug***
StreamResult consoleResult = new StreamResult(pstream);
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer = transformerFactory.newTransformer();
Thread.sleep(100);
***transformer.transform(dmsource, consoleResult);***
//out.println("println this is a testprogram"); // client receive ok
pstream.flush();
System.out.println(connectionname + ": reply sent.");
if (inputLine == endOfCom){
System.out.println(connectionname + ": is satisfied and terminated communication.");
break;
}
}
pstream.close();
csocket.close();
}catch (IOException e) {
System.out.println(e);
}catch (Exception e) {
System.out.println(e);
}
}
}
And the android client code as below:
public void run() {
if (barcode.length() > 0) {
Socket socket = null;
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
socket.setSoTimeout(10000);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out.write(barcode + ENDL);
if(out.checkError()){
showToUI("PrintWriter had error");
} else {
showToUI("Query sent");
}
int i = 0;
while (true) {
try{
if (**(serverResponse = in.readLine()) != null**) {
if(serverResponse == endOfCom){
Log.i("communicated all data", "bye");
out.write(endOfCom + ENDL);
break;
} else{
}
Log.i("server says", serverResponse);
}
//Log.i("server says", (serverResponse == null? "null" :serverResponse ));
}catch(SocketTimeoutException e){
showToUI(barcode + ": Server did not respond in time");
if (i++ > 2) {
break;
}
}
}
} catch (final UnknownHostException e1) {
showToUI(e1.toString());
} catch (final IOException e1) {
showToUI(e1.toString());
} finally{
try {
socket.close();
} catch (IOException e) {
showToUI(e.toString());
}
}
}else{
runOnUiThread(new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Please enter something in barcode", Toast.LENGTH_SHORT).show();
}
});
}
}
I have tested that the xml result returned was ok, if the Stream Result was set to System.out instead of the PrintStream pstream, everything prints perfectly to the console.
However with or without pstream.flush(), client received no response at (serverResponse = in.readLine()) != null.
Also the PrintWriter out which was based on the same Socket socket of pstream successfully gave feedback to the client. When out.println("println this is a testprogram"); was called, the client received log at the Log.i("server says", serverResponse); line OK.
One thing to note is that the reply is usually quite long, can be up to 65536 characters or even more, I do not know if that has any implication, I have tried to create a Buffered reader on the android app larger than the replying xml, it still did not work. The machines are communicating on local network, java server program is running on a different machine from the android emulator.
Any help is appreciated, this had been going on for days and nowhere.
readLine() won't return null until the peer closes the connection. And when it does return null, you need to break out of the loop. And don't compare string s with ==.
what it do..
1. an iterative dictionary server that is listening clients requests..
2. connection will be established..
3. server will accept input string from client..
4. then server will search meaning of string from a file..
5. then server will return meaning to the client..
problem is with the while loop of server.. if it finds word it will send that word's meaning to client..fine.. but if word is not found... this
if(d.equals(null)){
input="No knowledge";
out.println(input);
out.flush();
}
doesn't execute... client says null and server says null exception...
what i am doing wrong here... i'm not getting it...!!
i have tried to changed this code...
client-server online dictionary program in java
client:
import java.io.;
import java.net.;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class DCC1 {
public static void main(String[] args) throws IOException {
final int PORT = 8888;
Socket s = null;
PrintWriter out = null;
try {
s = new Socket("localhost", PORT);
out = new PrintWriter(s.getOutputStream()); // Output stream to the server
}
catch (UnknownHostException ex) {
System.err.println("Unknown host: " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
catch (IOException ex) {
System.err.println("Cannot get I/O for " + PORT);
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
Scanner user = new Scanner(System.in); // Scanning for user input
System.out.print("Enter String: ");
String input;
input = user.next(); // Hold the input from the user
out.println(input); // Send it to the server
out.flush();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream( )));
System.out.println(br.readLine());
out.close();
s.close();
}
}
server:
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class DSC1
{
public static void main(String[] args) throws IOException
{
final int PORT = 8888;
final String FILE_NAME = "dictionary.dat";
ServerSocket server = new ServerSocket(PORT);
Socket s = null;
PrintWriter out = null;
Scanner in = null;
FileInputStream fin = null;
ObjectInputStream oin = null;
while (true)
{
try
{
s = server.accept();
}
catch (IOException ex)
{
System.err.println("Accept failed");
System.err.println("Exception: " + ex.getMessage());
System.exit(1);
}
System.out.println("Accepted connection from client");
try
{
in = new Scanner(s.getInputStream()); // Input stream from the client
out = new PrintWriter(s.getOutputStream()); // Output stream to the client
String temp = in.next(); // String holding the word sent from the client
System.out.println("From the client " + temp);
String input = null;
fin = new FileInputStream(FILE_NAME);// The dictionary file
oin = new ObjectInputStream(fin);
dictionary d = (dictionary)oin.readObject();
while(d!= null)
{
System.out.println("in loop...");
if(d.name.equals(temp)){
input=d.meaning;
d.printDic();
out.println(input);
out.flush();
break;
}
d = (dictionary)oin.readObject();
if(d.equals(null))
{
input="No knowledge";
out.println(input);
out.flush();
}
}
}
catch (ClassNotFoundException|IOException ex)
{
System.err.println("Exception: " + ex.getMessage());
System.out.println("Closing connection with client");
in.close();
System.exit(1);
}
in.close();
}
}
}
Don't use d.equals(null). If you want to check if d is null, just do if (d==null).
Why? There's no way this can return true, so probably that's the reason why this code never executes and you don't get what you expect.
I want to access an arbitrary webpage using sockets (as a learning mechanism for myself). The code below does not work, what am I doing wrong?
import java.net.*;
import java.io.*;
public class Example
{
public static void main(String args[]) throws Exception
{
Socket socket =
new Socket("www.google.com", 80);
PrintWriter out =
new PrintWriter(socket.getOutputStream(), true);
BufferedReader reader =
new BufferedReader(
new InputStreamReader(socket.getInputStream()));
BufferedReader stdIn =
new BufferedReader(
new InputStreamReader(System.in));
String userInput;
while ((userInput = stdIn.readLine()) != null) {
out.println("GET / HTTP/1.1 \\r\\n Host: www.google.com \\r\\n\\r\\n");
System.out.println("echo: " + reader.readLine());
}
}
}
After trying for a couple hours I was unable to figure out what exactly I was doing wrong. All I want is Google's or some other websites homepage. Can anyone help me?
You might try something like the following (using sockets)
package com.example.webpagesocket;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
public class GetWebPageUsingSockets {
public static void main(String[] args) {
String urlString;
urlString = "www.google.com";
accessWeb(urlString);
}
private static void accessWeb(String urlString) {
String host;
String page;
int slashLoc;
// Set up encoding and decoding
Charset charset = Charset.forName("ISO-8859-1");
CharsetDecoder decoder = charset.newDecoder();
CharsetEncoder encoder = charset.newEncoder();
if ((slashLoc = urlString.indexOf('/')) < 0) {
host = urlString;
page = "";
} else {
host = urlString.substring(0, slashLoc);
page = urlString.substring(slashLoc);
}
System.out.println("Accessing web page demonstration");
System.out.println("Host: '" + host + "' Page: '" + page + "'");
SocketChannel channel = null;
try {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
CharBuffer charBuffer = CharBuffer.allocate(1024);
InetSocketAddress socketAddress = new InetSocketAddress(host, 80);
channel = SocketChannel.open();
channel.connect(socketAddress);
String request = "GET " + page + " \r\n\r\n";
channel.write(encoder.encode(CharBuffer.wrap(request)));
while ((channel.read(buffer)) != -1) {
buffer.flip();
decoder.decode(buffer, charBuffer, false);
charBuffer.flip();
System.out.println(charBuffer);
buffer.clear();
charBuffer.clear();
}
} catch (UnknownHostException e) {
System.err.println(e);
} catch (IOException e) {
System.err.println(e);
} finally {
if (channel != null) {
try {
channel.close();
} catch (IOException ignored) {
}
}
}
System.out.println("\nDone.");
}
}
Edit : didn't notice the \ at first reading ...
It looks like you are continuously sending "GET / HTTP/1.1 \\r\\n Host: www.google.com \\r\\n\\r\\n" to the host (at each read). You'd better keeping it out of the loop and sent true carriage return + line feed and not printable chars \ r \ n :
out.println("GET / HTTP/1.1 \r\nHost: www.google.com\r\n\r\n");
String userInput;
while ((userInput = stdIn.readLine()) != null) {
You only start reading after sending your GET, but the socket will buffer data.
Server and client communicating with my own protocol which looks like XMPP. I should to realize chat application. So when one user write String it immedeatly should be sended to other client through the server. I have method sendToAll on server. But user see the message of other user only when it press enter.
How can user receive messages without pressing enter button?
So this is my client:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import org.apache.log4j.Logger;
import dataart.practice.protocols.XMLProtocol;
public class Client {
public static final String SERVER_HOST = "localhost";
public static final Integer SERVER_PORT = 4444;
public static final Logger LOG = Logger.getLogger(Client.class);
private static BufferedReader in;
private static PrintWriter out;
private static BufferedReader inu;
public static void main(String[] args) throws IOException {
System.out.println("Welcome to Client side");
XMLProtocol protocol = new XMLProtocol();
Socket fromserver = null;
fromserver = new Socket(SERVER_HOST, SERVER_PORT);
in = new BufferedReader(new InputStreamReader(fromserver.getInputStream()));
out = new PrintWriter(fromserver.getOutputStream(), true);
inu = new BufferedReader(new InputStreamReader(System.in));
String fuser, fserver;
while (true){
if(in.ready()){//fserver = in.readLine()) != null) {
System.out.println("asdasdsd");
fuser = inu.readLine();
if (fuser != null) {
if (fuser.equalsIgnoreCase("close"))
break;
if (fuser.equalsIgnoreCase("exit"))
break;
protocol.setComId((long) 0);
protocol.setContent(fuser);
protocol.setLogin("Guest");
try {
JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);
Marshaller jaxbMarshaller = jaxbContext.createMarshaller();
jaxbMarshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);
jaxbMarshaller.marshal(protocol, out);
out.flush();
} catch (JAXBException e) {
LOG.error("Error while processing protocol" + e);
}
}
}
}
out.close();
in.close();
inu.close();
fromserver.close();
}
}
And Server with ServerThread.
public static void main(String[] args) throws IOException {
LOG.trace("Server started");
ServerSocket s = new ServerSocket(SERVER_PORT);
try {
while (true) {
LOG.trace("Waiting for connections...");
Socket socket = s.accept();
try {
// new ServerThread(socket);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream())), true);
userCounter++;
addUser("Guest" + userCounter, out);
LOG.trace("User " + userCounter + " has been added!");
exec.execute(new ServerThread(socket, in, out));
} catch (IOException e) {
socket.close();
}
}
} finally {
s.close();
}
}
ServerThread.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.Socket;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.stream.StreamSource;
import org.apache.log4j.Logger;
import dataart.practice.protocols.XMLProtocol;
import dataart.practice.serverUtils.Commands;
public class ServerThread implements Runnable {
private static final Logger LOG = Logger.getLogger(ServerThread.class);
private XMLProtocol protocol;
private Socket socket;
private BufferedReader in;
private PrintWriter out;
private String buffer = "";// may be exist another. way but it's not working
private Boolean login = false;
public ServerThread(Socket s, BufferedReader in, PrintWriter out) throws IOException {
this.in = in;
this.out = out;
out.println("</XMLProtocol>");
socket = s;
new Thread(this);
}
public void run() {
try {
while (true) {
if ((buffer = in.readLine()) != null) {
if (buffer.endsWith("</XMLProtocol>")) {
protocol = getProtocol(buffer);
//Server.onlineUserList.put(protocol.getLogin(), out);
/* if (!login){
out.println("Maybe login first?");
}
*/
LOG.trace("Getting message from user: " + protocol.getLogin() + " recived message: " + protocol.getContent());
///out.println(protocol.getLogin() + " says:" + protocol.getContent());
Server.sendToAll(protocol.getContent()+"</XMLProtocol>");
} else {
LOG.trace("Nop protocol do not send with it end");
}
}
}
} catch (IOException e) {
LOG.error("Error in reading from stream: " + e);
} catch (JAXBException e) {
LOG.error("Error in Marshalling: " + e);
} finally {
try {
socket.close();
LOG.trace("Socket closed");
} catch (IOException e) {
LOG.error("Socket no closed" + e);
}
}
}
public XMLProtocol getProtocol(String buffer) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(XMLProtocol.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
return (XMLProtocol) jaxbUnmarshaller.unmarshal(new StreamSource(new StringReader(buffer)));
}
public Boolean loginIn(XMLProtocol protocol) {
return true;
}
}
You will need to multi-thread both the client and server. The client will need one thread that listens for messages from the server and writes them to his/her screen and one thread that waits for his/her keyboard input and sends it to the server. Likewise for each connection to the server, it will need a thread waiting for input from the client and one thread sending output from other users to the client.
The reason you don't see incoming messages until you press enter is because of the client while loop. It's commented out now, but it looks like your loop used to:
- Read incoming messages from server
- Read input from keyboard
- Send input to server
So you read whatever was available from the server, and then the client waits for more keyboard input before reading from the server again (in the next iteration).
Another word of advice, from my understanding, creating JAXBContext can be an expensive operation. You don't need to recreate it every time you send a message. Consider initializing one in your server and client and then reusing it for each marshall/unmarshall.
Try this,
Do Not use BufferedReader() with PrintWriter..... PrintWriter is itself the Bridge between byte level socket data and character form.
Eg:
I am showing for a single client, use the while loop for n nos of clients
ServerSocket s = new ServerSocket(4444);
Socket incoming = s.accept();
OutputStream output = s.getOutputStream();
PrintWriter pw = new PrintWriter(output,true);
System.out.println(pw.write(new Scanner(System.in).nextLine()));
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.)