I'm trying to develop a simple Java file transfer application using TCP.
My current server code is as follows:
package tcp.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args) {
new FTPServer().go();
}
void go() {
try {
ServerSocket server = new ServerSocket(2015);
System.out.println("server is running ....!");
while (true) {
Socket socket = server.accept();
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String file = reader.readLine();
System.out.println("file to be downloaded is : " + file);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
//bos.close();
}
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Using my current server code above, the downlloding does not work as expected. the above code sends part of the file to the client , not the entire file. Note that I used the flush method to flush the buffer. but when I replace the flush () method by the close () method, the file is fully sent to the client whithout any loss. Could anyone please explain this behavior!
UPDATE: Here is the code of my client:
package tcp.ftp;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
/**
*
* #author aaa
*/
public class FTPClient {
public static void main(String[] args) {
String file = "JasperReports-Ultimate-Guide-3.pdf";
try {
InetAddress address = InetAddress.getLocalHost();
Socket socket = new Socket(address, 2015);
System.out.println("connection successfully established ....!");
PrintWriter pw = new PrintWriter(socket.getOutputStream());
pw.println(file);
pw.flush();
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy" + file));
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
System.out.println("file download is complete ...!");
} catch (UnknownHostException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
}
Another behavior without the use of Socket. take the following code that copy a file from a source to a destination:
public class CopieFile {
static void fastCopy(String source, String destination) {
try {
FileInputStream fis = new FileInputStream(source);
BufferedInputStream bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(destination);
BufferedOutputStream bos = new BufferedOutputStream(fos);
while (true) {
int octet = bis.read();
if (octet == -1) {
break;
}
bos.write(octet);
}
bos.flush();
} catch (FileNotFoundException ex) {
System.out.println(ex.getMessage());
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) throws IOException {
String source = "...";
String destination = "...";
fastCopy(source, destination);
}// end main
}// end class
the above code to copy a file from one location to another without any loss. Note well that I did not close the stream.
If you never close the stream the client wil never get end of stream so it will never exit the read loop.
In any case the stream and the socket are about to go out of scope, so if you don't close them you have a resource leak.
Related
I'm trying made a simple video stream with Java.I got that play some mp4 video,but not all. On the other hand, I can't seek the stream when the video is playing(Tried in VLC and Chrome). I like to know: What problems does my code have?
Here is the code:
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.net.ServerSocket;
import java.net.Socket;
public class Xerver {
protected void start() {
ServerSocket s;
Socket remote;
OutputStream out;
System.out.println("Webserver starting up on port 8080");
try {
// create the main server socket
s = new ServerSocket(8080);
} catch (IOException e) {
System.out.println("Error: " + e);
return;
}
System.out.println("Waiting for connection");
for (;;) {
try {
// wait for a connection
remote = s.accept();
// remote is now the connected socket
System.out.println("Connection, sending data.");
BufferedReader in = new BufferedReader(new InputStreamReader(remote.getInputStream()));
FileInputStream fs;
out = remote.getOutputStream();
File file = new File("D:\\stream.mp4");
out.write("HTTP/1.0 200 OK\r\n".getBytes());
out.write("Content-Type: video/mp4\r\n".getBytes());
out.write("Accept-Ranges: bytes\r\n".getBytes());
out.write(String.format("Content-Length:%s\r\n\r\n",Long.toString(file.length())).getBytes());
fs = new FileInputStream(file);
final byte[] buffer = new byte[1024];
int count = 0;
do{
count = fs.read(buffer);
out.write(buffer, 0, count);
}
while (count <= 1024);
out.flush();
remote.close();
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
public static void main(String args[]) {
Xerver ws = new Xerver();
ws.start();
}
}
Thanks in advance
I have send a image that is about 500kb but in the server ,the image that receive is more than 500kb.I wonder that is there any logical problems I had made? the speed of the network is about 100kb/s.
the client
package client;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.OutputStreamWriter;
import java.net.Socket;
public class client {
public static void main(String[] args) {
Socket s = null;
BufferedOutputStream bo = null;
BufferedInputStream bi = null;
try {
s = new Socket("127.0.0.1",12349);
bo = new BufferedOutputStream(s.getOutputStream());
bi = new BufferedInputStream(new FileInputStream("1.jpg"));
byte [] bys =new byte[1024];
while((bi.read(bys))!=-1){
bo.write(bys);
}
bo.flush();
System.out.println("already post the image");
bi.close();
} catch (IOException e) {
}finally{
try {
s.close();
} catch (IOException e) {
System.out.println("close failed");
}
}
}
}
server
package server;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class sserver {
public static void main(String[] args) {
ServerSocket ss = null;
Socket s = null;
BufferedOutputStream bo = null;
BufferedInputStream bs = null;
try {
ss = new ServerSocket(12349);
s = ss.accept();
bo = new BufferedOutputStream(new FileOutputStream("2.jpg"));
bs = new BufferedInputStream(s.getInputStream());
byte [] bys =new byte[1024];
while((bs.read(bys))!=-1){
bo.write(bys);
}
bo.flush();
System.out.println("upload success");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
try {
ss.close();
} catch (IOException e) {
System.out.println("close failed");
}
}
}
}
The problem is that you are disregarding the number of bytes read:
while((bi.read(bys))!=-1){
bo.write(bys);
}
This means that you always write 1024 bytes to bo, even if you read fewer than 1024 bytes from bi.
You need to assign the number of bytes read to a variable, and pass that to the write call:
int bytesRead;
while((bytesRead = bi.read(bys))!=-1){
bo.write(bys, 0, bytesRead);
}
Please write exacte byte which you received like below
int len= 0 ;
while( ( len = bi.read(bys))!=-1){
bo.write(bys,0, len);
}
Same code change required in both client and server side. I tested at my end and found that both file has same size afterthis change
Your server code is always writing full length of bys array into output stream.
Proper way to do it:
byte [] bys =new byte[1024];
while(true) {
int numRead = bs.read(bys);
if (numRead == -1)
break;
bo.write(bys, 0, numRead);
}
I am trying to implement FTP protocol using socket programing in java. I am using the ObjectOutputStream to write the data requested to the socket in the server side but i am getting the following error on the console window..
Software caused connection abort: socket write error
Here is the implementation of my program
Server side:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
public class FTPServer {
public static void main(String[] args) {
try {
#SuppressWarnings("resource")
ServerSocket ss = new ServerSocket(4550);
while(true) {
Socket socket = ss.accept();
BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
FileInstance file = new FileInstance();
System.out.println(file.srcDir = br.readLine());
System.out.println(file.destDir = br.readLine());
System.out.println(file.filename = file.srcDir.substring(file.srcDir.lastIndexOf("/") + 1));
File f = new File(file.srcDir);
byte[] bytes = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(bytes);
file.FILE_SIZE = bytes.length;
file.fileData = bytes;
ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
oos.writeObject(file);
System.out.println("Success");
oos.close();
fis.close();
br.close();
}
} catch(IOException e) {
System.out.println(e.getMessage());
}
}
}
Client Side:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.PrintWriter;
import java.net.Socket;
public class FTPClient {
public static void main(String[] args) {
try {
Socket socket = new Socket("127.0.0.1", 4550);
BufferedReader sbr = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the path of requested file");
String path = sbr.readLine();
System.out.println(path);
PrintWriter pw = new PrintWriter(socket.getOutputStream(), true);
System.out.println("Enter Destination");
path = path + "\n" + sbr.readLine();
System.out.println(path);
pw.write(path);
pw.close();
sbr.close();
// receive file
ObjectInputStream ois= new ObjectInputStream(socket.getInputStream());
FileInstance file = (FileInstance)ois.readObject();
ois.close();
if(!new File(file.destDir).exists())
new File(file.destDir).mkdir();
File nfile = new File(file.destDir + "/" + file.filename);
FileOutputStream fos = new FileOutputStream(nfile);
fos.write(file.fileData);
fos.close();
socket.close();
System.out.println("Success");
} catch(IOException e) {
System.out.println(e.getMessage());
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
}
}
this is the FileInstance class......
import java.io.Serializable;
public class FileInstance implements Serializable {
private static final long serialVersionUID = 1L;
public String destDir;
public String srcDir;
public String filename;
public long FILE_SIZE;
public byte[] fileData;
public String status;
}
You have two problems in FTPClient
You are closing the socket prematurely. At line 22 pw.close() needs to be pw.flush()
Even after you fix the first issue the server will hang. You need to add a newline to the end of the path string you send so the server, using readLine(), can read entire lines; otherwise it waits forever for a complete line that never arrives.
This was trivial to debug in Eclipse. If you want to be a good developer, debugging skills are crucial. Set more than one breakpoint and see what happens. Experiment. Play. Learn.
I have a Client-Server programm. The Client-programm sends a file to the server and the server receives the file. my problem is, that the file is not really receiving on the server...I't creates a file.txt in the server-directory, but it is empty...(yes i'm sure that ne file.txt in the client-directory is not empty ;) )
I think the problem is the while-loop in Client.java, because it is never embarrassed....
For the future i implements now on the server side one thread per receiving file.
The client-programm:
package controller;
public class Main {
public static void main(String[] args) {
new Controller();
}
}
-
package controller;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.Socket;
import java.net.UnknownHostException;
public class Controller {
public Controller() {
try {
sendFileToServer();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendFileToServer() throws UnknownHostException, IOException {
Socket socket = null;
String host = "localhost";
socket = new Socket(host, 5555);
String filename = "file.txt";
File file = new File(filename);
OutputStream outText = socket.getOutputStream();
PrintStream outTextP = new PrintStream(outText);
outTextP.println(filename);
long filesize = file.length();
byte[] bytes = new byte[(int) filesize];
FileInputStream fis = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(fis);
BufferedOutputStream out = new BufferedOutputStream(socket.getOutputStream());
int count;
System.out.println("Start sending file...");
while ((count = bis.read(bytes)) > 0) {
System.out.println("count: " + count);
out.write(bytes, 0, count);
}
System.out.println("Finish!");
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
}
}
-
The server-programm:
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException {
new Server();
}
}
-
public class Server {
private ServerSocket serverSocket;
public Server() {
try {
serverSocket = new ServerSocket(5555);
waitForClient();
} catch (IOException e) {
e.printStackTrace();
}
}
private void waitForClient() {
Socket socket = null;
try {
while(true) {
socket = serverSocket.accept();
Thread thread = new Thread(new Client(socket));
thread.start();
}
} catch (IOException ex) {
System.out.println("serverSocket.accept() failed!");
}
}
}
-
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.Socket;
public class Client implements Runnable{
private Socket socket;
public Client(Socket socket) {
this.socket = socket;
}
#Override
public void run() {
receiveFile();
}
private void receiveFile() {
try {
InputStream is = null;
FileOutputStream fos = null;
BufferedOutputStream bos = null;
int bufferSize = 0;
InputStream outText = socket.getInputStream();
// Get filename
InputStreamReader outTextI = new InputStreamReader(outText);
BufferedReader inTextB = new BufferedReader(outTextI);
String dateiname = inTextB.readLine();
System.out.println("Dateiname: " + dateiname);
try {
is = socket.getInputStream();
bufferSize = socket.getReceiveBufferSize();
System.out.println("Buffer size: " + bufferSize);
} catch (IOException ex) {
System.out.println("Can't get socket input stream. ");
}
try {
fos = new FileOutputStream(dateiname);
bos = new BufferedOutputStream(fos);
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
byte[] bytes = new byte[bufferSize];
int count;
while ((count = is.read(bytes)) > 0) {
bos.write(bytes, 0, count);
System.out.println("This is never shown!!!"); // In this while-loop the file is normally receiving and written to the directory. But this loop is never embarrassed...
}
bos.flush();
bos.close();
is.close();
socket.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
When you do these kind of transfers you have to keep in mind that there is a difference between a socket's close and shutdown, in your code you close the socket in the client.
So lets see what happens : you fill in the buffers then you tell the socket to close which will discard the operation you just asked for.
When you shutdown you tell the socket "I won't send more data but send what's left to be sent and shut down" so what you need to do is to shut down the socket before you close it so the data will arrive.
So instead of this
out.flush();
out.close();
fis.close();
bis.close();
socket.close();
Try it with this
out.flush();
socket.shutdownInput(); // since you only send you may not need to call this
socket.shutdownOutput(); // with this you ensure that the data you "buffered" is sent
socket.close();
Generally if you want a graceful close, you should do it like this in all cases even for the server, so what you did is usually okay if there is an error and you just close the connection since you cant recover from an error.
i'm making a program/game that will update automatically. i have the update part down, but not the checking of the version. i would have thought that it'd be pretty easy. heres what i've done. i wrote an updater for the game, and i wrote a server. the server starts a thread every time a client/updater connects. the thread handles everything. the game updater reads a file called version.txt and that provides the version number (default 0.0.1) and sends it to the server. the server does recieve the version, and will System.out.println(); if the version matches, and if i change the version, it changes the output. so that part works. but that is as far as it goes. the second part of the process is that the server then sends just a text file called NPS Game.txt (it sends anything, but txt was easy to test with) and the client replaces the old version of this file with the new one that just sent. the problem is that i keep getting an error that says the Socket is closed. i've tried using socket.setKeepAlive(true); but that didnt change anything (i put that on both the client and the server). here is the code:
server:
package main;
import java.io.*;
import java.net.*;
import javax.swing.JOptionPane;
public class Server {
static ServerSocket serverSocket = null;
static Socket clientSocket = null;
static boolean listening = true;
public static void main(String[] args) throws IOException {
try {
serverSocket = new ServerSocket(6987);
} catch (IOException e) {
ServerThread.showmsg("Could not use port: 6987");
System.exit(-1);
}
ServerThread.showmsg("server- initialized");
ServerThread.showmsg("server- waiting...");
while (listening)
new ServerThread(serverSocket.accept()).start();
}
}
server thread:
package main;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import javax.swing.JOptionPane;
public class ServerThread extends Thread {
Socket socket;
ObjectInputStream in;
ObjectOutputStream out;
String version = "0.0.1";
public ServerThread(Socket socket) {
super("Server Thread");
this.socket = socket;
}
public void run() {
showmsg("server- Accepted connection : " + socket);
getVersion();
sendFile();
}
public void getVersion() {
try {
ObjectInputStream ois = new ObjectInputStream(
socket.getInputStream());
try {
String s = (String) ois.readObject();
if (s.equals(version)) {
System.out.println("server- matched version :)");
} else {
System.out.println("server- didnt match version :(");
System.exit(0);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
ois.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public void sendFile() {
// sendfile
File myFile = new File("C:\\Programming\\NPS\\Files\\bin\\NPS Game.txt");
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis;
try {
fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
showmsg("server- Sending...");
os.write(mybytearray, 0, mybytearray.length);
os.flush();
socket.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void showmsg(String s) {
JOptionPane.showMessageDialog(null, s);
}
}
and the client/updater:
package main;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import org.omg.CORBA.portable.InputStream;
public class Connections {
String IP, port;
String message = "";
Socket socket;
public Connections(boolean server, boolean updating, String IP, String port) {
this.IP = IP;
this.port = port;
try {
socket = new Socket(IP, Integer.parseInt(port));
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if (!server) {
if (updating) {
try {
sendVersion();
updating();
} catch (IOException e) {
e.printStackTrace();
}
} else {
client();
}
}
if (server) {
}
}
public void sendVersion() throws IOException {
FileReader fileReader = new FileReader(
"C:\\Program Files\\AVTECH\\NPS\\Files\\bin\\version.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String stringRead = bufferedReader.readLine();
bufferedReader.close();
ObjectOutputStream oos = new ObjectOutputStream(
socket.getOutputStream());
oos.writeObject(stringRead);
oos.flush();
oos.close();
}
public void updating() throws IOException {
int filesize = 6022386; // filesize temporary hardcoded
int bytesRead;
int current = 0;
showmsg("client- connected");
// receive file
byte[] byteArray = new byte[filesize];
java.io.InputStream inStream = socket.getInputStream();
FileOutputStream fileOutStream = new FileOutputStream(
"C:\\Program Files\\AVTECH\\NPS\\Files\\bin\\NPS Game.txt");
BufferedOutputStream buffOutStream = new BufferedOutputStream(
fileOutStream);
bytesRead = inStream.read(byteArray, 0, byteArray.length);
current = bytesRead;
do {
bytesRead = inStream.read(byteArray, current,
(byteArray.length - current));
if (bytesRead >= 0)
current += bytesRead;
} while (bytesRead > -1);
buffOutStream.write(byteArray, 0, current);
buffOutStream.flush();
buffOutStream.close();
inStream.close();
socket.close();
}
public static void showmsg(String s) {
JOptionPane.showMessageDialog(null, s);
}
}
i dont know what's wrong with it, but it is really frusturating. if anyone can help, it would be appreciated. some things ive done: google all kinds of questions, tried implementing socket.setKeepAlive(true);. also, i thought it might be of note, in the server thread, right above the line BufferedInputStream bis = new BufferedInputStream(fis);, i put System.out.println(socket.isClosed); and it returned true. thats all i have. thanks in advance!
I think that closing one of both streams, closes the socket. So try to remove the ois.close() call out of your getVersion() method at the server side. Also get rid of the oos.close() call in your sendVersion() method at the client side.
When you construct an ObjectOutputStream or ObjectInputStream and you are done with it, you shouldn't close that stream, because it will close the underlying stream, which is in your case the socket.