Transfering files from client to server. Program stops on InputStream.read() - java

My program stops on the line:
int file = is.read();
And I don't know why.
-client:
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;
public class Main {
#SuppressWarnings("resource")
public static void main(String[] args) throws UnknownHostException, IOException {
Socket sock = new Socket("localhost", 5000);
String FileName = "Manik.txt";
File MyFile = new File(FileName);
int FileSize = (int) MyFile.length();
OutputStream os =sock.getOutputStream();
PrintWriter pr = new PrintWriter(sock.getOutputStream(), true);
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(MyFile));
Scanner in = new Scanner(sock.getInputStream());
pr.println(FileName);
pr.println(FileSize);
byte[] filebyte = new byte[FileSize];
bis.read(filebyte, 0, filebyte.length);
os.write(filebyte, 0, filebyte.length);
System.out.println(in.nextLine());
os.flush();
sock.close();
}
}
Server:
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
public class Server
{
public static void main(String[] Args) throws IOException
{
try (ServerSocket servsock = new ServerSocket(5000))
{
Socket sock = servsock.accept();
System.out.println("FFFF");
Scanner in = new Scanner(sock.getInputStream());
InputStream is = sock.getInputStream();
PrintWriter pr = new PrintWriter(sock.getOutputStream(), true);
String FileName = in.nextLine();
int FileSize = in.nextInt();
FileOutputStream fos = new FileOutputStream(FileName);
BufferedOutputStream bos = new BufferedOutputStream(fos);
byte[] filebyte = new byte[FileSize];
int file = is.read();
bos.write(filebyte, 0, file);
System.out.println("Incoming File: " + FileName);
System.out.println("Size: " + FileSize + "Byte");
if(FileSize == file)System.out.println("File is verified");
else System.out.println("File is corrupted. File Recieved " + file + " Byte");
pr.println("File Recieved SUccessfully.");
bos.close();
sock.close();
}
}
}

Related

problems with sending String via socket in java

hi everyone i have problems with sending 2 strings via socket in java.
i have UI that get Username and password from client and send it to server . my problem make 2 part :1-i can not get the string username in my server 2- when the client send the username the socket is close before send the password here is my code please help me .
the main purpose is getting 2 string username and password from UI (client)and send them by socket to server.
Server:
package finalproject;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class Server
{
ServerSocket listener;
Socket socket;
OutputStream out ;
InputStream in;;
InputStreamReader reader;
OutputStreamWriter writer;
String massage;
public void connectserver() throws IOException
{
listener = new ServerSocket(9097);
System.out.println("Server is running on port 9097 ...");
}
public void waitforclient() throws IOException
{
socket = listener.accept();
System.out.println("A new client connected to the server");
}
public void startstreamsserver() throws IOException
{
in = socket.getInputStream();
out = socket.getOutputStream();
writer = new OutputStreamWriter(out);
reader = new InputStreamReader(in);
System.out.println("Server streams are ready");
}
public void closestreamsserver() throws IOException
{
writer.close();
reader.close();
}
public void getinfoserver() throws IOException
{
try
{
reader.read();
System.out.println(reader);
System.out.println("input is : " + reader.toString());
}
catch(IOException IOE)
{
IOE.printStackTrace();//if there is an error, print it out
}
}
}
Client:
package finalproject;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
public class Client
{
Socket socket;
OutputStream out1;
InputStream in1;
OutputStreamWriter writer;
InputStreamReader reader;
String massage;
JFrame frame;
BorderLayout blayout;
JButton center;
JButton south;
FlowLayout fLoyout;
JLabel jb1;
JTextField name;
JLabel jb2;
JTextField pass;
JLabel jb7;
JPanel cpanel;
JPanel spanel;
public void connectclient() throws IOException
{
socket = new Socket("localhost", 9097);
System.out.println("connect to server on port 9097");
}
public void startstreamsclient() throws IOException
{
in1 = socket.getInputStream();
out1 = socket.getOutputStream();
writer = new OutputStreamWriter(out1);
reader = new InputStreamReader(in1);
System.out.println("Client streams are ready");
}
public void closestreamsclient() throws IOException
{
writer.close();
reader.close();
}
public void loginformclient()
{
frame = new JFrame();
frame.setVisible(true);
frame.setSize(500, 600);
blayout = new BorderLayout();
center = new JButton();
south = new JButton();
frame.setLayout(blayout);
fLoyout = new FlowLayout(FlowLayout.CENTER);
center.setLayout(fLoyout);
south.setLayout(fLoyout);
jb1 = new JLabel("Username :");
name = new JTextField(20);
center.add(jb1);
center.add(name);
jb2 = new JLabel("Password :");
pass = new JTextField(30);
center.add(jb2);
center.add(pass);
jb7 = new JLabel("Save");
south.add(jb7);
cpanel = new JPanel();
cpanel.add(center);
spanel = new JPanel();
south.addActionListener((ActionEvent ae) -> {
try
{
writer.write(name.getText());
writer.flush();
writer.write(pass.getText());
writer.flush();
writer.close();
}
catch (IOException ex)
{
Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex);
}
});
spanel.add(south);
cpanel.setLayout(new BoxLayout(cpanel, BoxLayout.Y_AXIS));
frame.add(cpanel, BorderLayout.CENTER);
frame.add(spanel, BorderLayout.SOUTH);
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
and my main class :
package finalproject;
import java.io.IOException;
import javax.swing.JFrame;
public class Finalproject
{
public static void main(String[] args) throws IOException
{
//build Server & Client
Server server = new Server();
Client client = new Client();
//Start Server & Client
server.connectserver();
client.connectclient();
//Server wait for new connection
server.waitforclient();
//start the Streams
client.startstreamsclient();
server.startstreamsserver();
//Client send login information to Server
client.loginformclient();
//Server get information
server.getinfoserver();
}
}
but the my inputs in my server are:
java.io.InputStreamReader#171fc7e
input is : java.io.InputStreamReader#171fc7e
Edited Based on EJP correct remark:
Add new line delimiter:
writer.write(name.getText() + System.lineSeparator());
writer.write(pass.getText());
writer.flush();
replace this:
reader = new InputStreamReader(in);
System.out.println("Server streams are ready");
with:
BufferedReader in = new BufferedReader(reader);
String username= in.readLine();
String password = in.readLine();

Can't set ImageView photo from datainputstream JavaFx socket application

I am trying to output an image to an ImageView in javafx, i am recieving the image via socket connection and saving it to my hard-drive then i create an Image object with the path of the newly created image, the problem is that the image view is not updated.
public void save(String path, DataInputStream dis) throws IOException {
FileOutputStream fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
//Image imBuff = ImageIO.read(socket.getInputStream());
int filesize = dis.readInt(); // Send file size in separate msg
byte[] buffer = new byte[filesize];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
totalRead += read;
remaining -= read;
//System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
System.err.println("img"+(frame_number)+".jpg");
fos.flush();
}
fos.flush();
fos.close();
System.out.println("frame num:"+frame_number);
Image i = new Image("Camera_Frame.jpg");
try{
//i=new Image("img"+frame_number+".jpg");
File f = new File("img"+frame_number+".jpg");
i = new Image(f.toURI().toString());
iv.setImage(i);
}catch(Exception e){
System.out.println("didn't find");
}
System.out.println("stream size:"+image_Stream.size());
ps.println("ok");
frame_number++;
}
Things i have tried:
1- i tried to used the path i saved the photo in to create an Image then used the setImage() function on my ImageView (iv), i got Invalid Url even though i loaded an image image from the same directory before.
2- we tried using (file:///) to get an absolute path but it didn't work, also invalid url
3- i tried loading the image as a file first then using the toURI() function to get the proper path to it then create an image accordingly, i don't get an error but it also doesn't update the UI
P.S
this function is called in a sub Thread that updates an ImageView in the main javafx thread, i tried it with images not loaded through the socket connection and it worked, but when i try to display the images i receive the face this problem.
EDIT: I managed to load the image properly, now i can't update the ImageView using iv.setImage()
EDIT:
CameraOBJ class
import java.awt.image.BufferedImage;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.net.Socket;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import javax.imageio.ImageIO;
import javafx.animation.AnimationTimer;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.stage.FileChooser;
import javafx.util.Duration;
public class CameraOBJ implements Runnable{
String name;
int delay;
Socket socket;
String ip;
int port;
PrintStream ps;
Scanner sc;
static int frame_number;
StackPane sp;
Label delay_lbl;
ImageView iv;
public CameraOBJ (String name, String ip, int port){
this.ip = ip;
this.port = port;
this.name = name;
sp = new StackPane();
}
public void run() {
setStackPane();
connect();
while(true){
update();
}
// Timeline timeline = new Timeline();
// Duration duration = Duration.seconds(1/Settings.FPS);
// KeyFrame f1 = new KeyFrame(duration,e->{
// update();
// });
// timeline.getKeyFrames().add(f1);
// timeline.setCycleCount(Timeline.INDEFINITE);
// timeline.play();
}
private void update() {
// Platform.runLater(new Runnable() {
// public void run() {
DataInputStream dis;
try {
dis = new DataInputStream(socket.getInputStream());
if(dis!=null){
save("images",dis);
//setStackPane();
}
} catch (IOException e1) {
System.out.println(e1.getMessage());
}
// }
// });
}
public void setStackPane(){
Platform.runLater(new Runnable() {
public void run() {
sp.setMinSize(500, 384);
sp.setMaxSize(500, 384);
sp.setStyle("-fx-background-color: #FFFFFF;");
Image image = new Image("Camera_Frame.jpg");
iv = new ImageView(image);
iv.setFitWidth(470);
iv.setPreserveRatio(true);
Label name_lbl = new Label(name);
delay_lbl = new Label(delay+"");
sp.setAlignment(iv,Pos.CENTER);
sp.setAlignment(name_lbl,Pos.TOP_LEFT);
sp.setAlignment(delay_lbl,Pos.BOTTOM_RIGHT);
sp.getChildren().addAll(iv,name_lbl,delay_lbl);
}
});
}
public void connect(){
try{
socket = new Socket(ip, port);
System.out.println(socket.isConnected());
ps = new PrintStream(socket.getOutputStream());
sc = new Scanner(socket.getInputStream());
}
catch (Exception c){
c.getMessage();
}
}
public void save(String path, DataInputStream dis) throws IOException {
Platform.runLater(new Runnable() {
public void run() {
FileOutputStream fos;
try {
fos = new FileOutputStream("src/img"+(frame_number)+".jpg");
int filesize;
try {
filesize = dis.readInt();
byte[] buffer = new byte[filesize];
int read = 0;
int totalRead = 0;
int remaining = filesize;
while ((read = dis.read(buffer, 0, Math.min(buffer.length, remaining))) >= 1) {
totalRead += read;
remaining -= read;
//System.out.println("read " + totalRead + " bytes.");
fos.write(buffer, 0, read);
System.err.println("img"+(frame_number)+".jpg");
fos.flush();
}
fos.flush();
fos.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
System.out.println("frame num:"+frame_number);
Image i = new Image("Camera_Frame.jpg");
try{
//i=new Image("file:img"+frame_number+".jpg");
File f = new File("C:\\Users\\ahmed\\workspace\\College\\RTS_Client\\src\\img"+frame_number+".jpg");
i = new Image(f.toURI().toString());
iv.setImage(i);
delay_lbl.setText("frame_number: "+frame_number);
}catch(Exception e){
System.out.println("didn't find");
}
frame_number++;
}
});
}
}
Main class:
import java.io.File;
import java.io.PrintStream;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;
import com.sun.prism.paint.Color;
import javafx.animation.AnimationTimer;
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.image.ImageView;
import javafx.scene.layout.Background;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class main extends Application{
static Stage window;
static String default_ip = "192.168.43.200";
static int default_port = 1234;
public static void main(String[] args) {
launch(args);
}
public void start(Stage stage) {
window = stage;
window.setResizable(false);
window.setTitle("Control Room");
StackPane sp = new StackPane();
sp.setMinSize(500, 500);
Scene sc = new Scene(sp);
window.setScene(sc);
window.show();
CameraOBJ camera = new CameraOBJ("Camera 1", default_ip, default_port);
Thread t = new Thread(camera);
camera.run();
sc = new Scene(camera.sp);
window.setScene(sc);
}
}
Server class:
import java.io.IOException;
import java.io.PrintStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.InputMismatchException;
import java.util.NoSuchElementException;
import java.util.Scanner;
public class Camera implements Runnable {
long timeStamp;
int delayShift;
int FPS;
boolean idle;
//Control Rooms object here
int portNumber;
Socket csocket;
Camera() {
}
Camera(Socket csocket) {
this.csocket = csocket;
}
void startConnection() throws Exception {
ServerSocket ssock = new ServerSocket(1234);
System.out.println("Listening");
while (true) {
Socket sock = ssock.accept();
System.out.println("Connected");
new Thread(new Camera(sock)).start();
}
}
public void run() {//Start Stream
try {
PrintStream pstream = new PrintStream(csocket.getOutputStream());
Scanner inpstream = new Scanner(csocket.getInputStream());
// Receiving an integer that is sent from the client side.
int ID = inpstream.nextInt();
// Generating a reply based on the ID sent from the client.
String response = "";
if (ID == 1100) {
response = "Your name is Mahmoud. \n" + "You are 22 years old.";
} else {
response = "No data found matching the ID you entered.";
}
// Sending the reply through the OutputStream to the client.
pstream.println(response);
pstream.close();
terminateConnection();
} catch (InputMismatchException e) {
System.out.println(e.toString() + "\nNo data is received.");
} catch (IOException e) {
System.out.println(e.toString());
} catch (Exception c) {
System.out.println(c.toString());
}
}
void terminateConnection() throws IOException {
csocket.close();
}
public static void main(String[] args) throws Exception {
Camera cam = new Camera();
cam.startConnection();
}
}

Java - sending a file over socket - file isn't received fully

i am really stuck with a little project i'm doing. I am trying to send music files (only .wav) over a socket from a server to a client. Everything works perfectly fine (i think...) except that the file that is received by the client isn't complete. I can't play the file and I can see that it is a bit smaller than the one the server has. What am I doing not right?
Here is the server code:
private Socket client;
private String filename;
private TBMCAudioServer ac;
private FileInputStream fis;
private BufferedOutputStream out;
int bufferSize = 0;
FileSender(Socket client, String filename, TBMCAudioServer ac){
this.client = client;
this.filename = filename;
this.ac = ac;
}
#Override
public void run(){
ac.ex.sendMessage(client, "[#preload#]" + filename);
File dir = new File(ac.getDataFolder() + File.separator + "music");
if(!dir.exists()){
dir.mkdir();
}
File file = new File(dir, filename + ".wav");
long length = file.length();
if(length > Integer.MAX_VALUE){
logger.info("File is too large.");
}
byte[] bytes = new byte[(int) length];
try{
fis = new FileInputStream(file);
out = new BufferedOutputStream(client.getOutputStream());
} catch (IOException e){
logger.info(e.getMessage());
}
int count;
try {
while((count = fis.read(bytes,0,bytes.length)) != -1){
out.write(bytes, 0, count);
}
out.flush();
out.close();
fis.close();
} catch (IOException e) {
logger.info(e.getMessage());
}
}
and here you can see my client code:
private Socket server;
private String filename;
private AudioClient ac;
InputStream is = null;
FileOutputStream fos = null;
int bufferSize = 0;
FileReceiver(Socket server, String filename, AudioClient ac){
this.server = server;
this.filename = filename;
this.ac = ac;
}
#Override
public void run() {
try{
is = server.getInputStream();
bufferSize = server.getReceiveBufferSize();
ac.logConsole("Buffer size: " + bufferSize);
} catch (IOException ex){
ac.logConsole(ex.getMessage());
}
try{
fos = new FileOutputStream(AudioClient.util.getLineValue(3) + filename + ".wav");
} catch (FileNotFoundException e){
ac.logConsole(e.getMessage());
}
byte[] bytes = new byte[bufferSize];
int count;
try {
while((count = is.read(bytes, 0, bytes.length)) != -1){
fos.write(bytes, 0, count);
}
ac.logConsole("yay");
is.close();
fos.flush();
fos.close();
} catch (IOException e) {
ac.logConsole(e.getMessage());
}
}
Okay I managed to send the file fully so I can see it has the same size as where it came from with my new code. The only problem is that i'm sending a music file and I can't play the file that is sent. Maybe someone knows what the problem is?
Server code:
package me.Ciaran.simplefileserver;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
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 = 13267; // you may change this
public final static String FILE_TO_SEND = "D:/server/plugins/TBMCAudioServer/music/DLTALL.wav"; // you may change this
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
final File myFile= new File(FILE_TO_SEND); //sdcard/DCIM.JPG
byte[] mybytearray = new byte[8192];
fis = new FileInputStream(myFile);
bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
try {
os = sock.getOutputStream();
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
int read;
while((read = dis.read(mybytearray)) != -1){
dos.write(mybytearray, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
and here is the client code:
package me.Ciaran.simplefileclient;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
public class SimpleFileClient {
public final static int SOCKET_PORT = 13267; // you may change this
public final static String SERVER = "127.0.0.1"; // localhost
public final static String
FILE_TO_RECEIVED = "C:/Users/Ciaran/Documents/TESTEN/music/DLTALL.wav"; // you may change this, I give a
// different name because i don't want to
// overwrite the one used by server...
public final static int FILE_SIZE = 6022386; // file size temporary hard coded
// should bigger than the file to be downloaded
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
InputStream in;
int bufferSize=0;
try {
bufferSize=sock.getReceiveBufferSize();
in=sock.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
System.out.println(fileName);
OutputStream output = new FileOutputStream(FILE_TO_RECEIVED);
byte[] buffer = new byte[bufferSize];
int read;
while((read = clientData.read(buffer)) != -1){
output.write(buffer, 0, read);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
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();
}
}
}

video file transfer using sockets

i have this code for transferring text files from server to client using sockets.i now want to transfer a video file from the server to client.how can i do that.how do i change my code to include video file?can anyone please help me.
server code
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 = 13267; //
public final static String FILE_TO_SEND = "c:/temp/source.pdf";
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.");
}
finally {
if (bis != null) bis.close();
if (os != null) os.close();
if (sock!=null) sock.close();
}
}
}
finally {
if (servsock != null) servsock.close();
}
}
}
client code
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 = 13267;
public final static String SERVER = "127.0.0.1";
public final static String
FILE_TO_RECEIVED = "c:/temp/source-downloaded.pdf";
public final static int FILE_SIZE = 6022386;
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();
}
}
}

Android send image over socket, received blank image

im trying to send image over socket in android using two emulator, log file give me
05-28 13:55:07.349: I/System.out(26763): Receiving...
and i can see the created image from file explorer in data\files\output.jpg but it's blank and it's size =0k
package com.javacodegeeks.android.androidsocketserver;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.os.StrictMode;
import android.util.Log;
public class Main extends Activity {
private static ServerSocket serverSocket;
private static Socket clientSocket;
private static InputStream inputStream;
private static FileOutputStream fileOutputStream;
private static BufferedOutputStream bufferedOutputStream;
private static int bufferSize = 3000; // bufferSize temporary hardcoded
private static int bytesRead;
private static int totalbytesRead = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
init();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void init() throws IOException {
// TODO Auto-generated method stub
serverSocket = new ServerSocket(6000); // Server socket
System.out.println("Server started. Listening to the port 4444");
clientSocket = serverSocket.accept();
byte[] data = new byte[bufferSize]; // create byte array to buffer the
// file
inputStream = clientSocket.getInputStream();
String filePath = this.getFilesDir().getPath().toString()
+ "/output.jpg";
fileOutputStream = new FileOutputStream(filePath);
// fileOutputStream = new FileOutputStream(file);
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
System.out.println("Receiving...");
// following lines read the input slide file byte by byte
bytesRead = inputStream.read(data,0,data.length);
totalbytesRead = bytesRead;
do {
bytesRead =
inputStream.read(data, totalbytesRead, (data.length-totalbytesRead));
if(bytesRead >= 0) totalbytesRead += bytesRead;
} while(bytesRead > -1);
bufferedOutputStream.write(data, 0 , totalbytesRead);
bufferedOutputStream.flush();
long end = System.currentTimeMillis();
System.out.println(end);
bufferedOutputStream.close();
System.out.println("Sever recieved the file");
}
}
and this is client side
package com.javacodegeeks.android.androidsocketclient;
/*
* This is a simple Android mobile client
* This application send any file to a remort server when the
* send button is pressed
* Author by Lak J Comspace
*/
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Transfer extends Activity {
private Socket client;
private FileInputStream fileInputStream;
private BufferedInputStream bufferedInputStream;
private OutputStream outputStream;
private Button button;
private TextView text;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transfer);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
button = (Button) findViewById(R.id.button1); // reference to the send
// button
text = (TextView) findViewById(R.id.textView1); // reference to the text
// view
// Button press event listener
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
File file = new File("Desktop:\\test.jpg"); // create file
// instance
client = new Socket("10.0.2.2", 5000);
byte[] mybytearray = new byte[(int) file.length()]; // create
// a
// byte
// array
// to
// file
fileInputStream = new FileInputStream(file);
bufferedInputStream = new BufferedInputStream(
fileInputStream);
outputStream = client.getOutputStream();
int read_count = 0;
while ((read_count = bufferedInputStream.read(mybytearray,
0, mybytearray.length)) != -1) {
outputStream.write(mybytearray, 0, read_count); // Now
// writes
// the
// correct
// amount
// of
// bytes
outputStream.flush();
}
outputStream.flush();
bufferedInputStream.close();
outputStream.close();
client.close();
text.setText("File Sent");
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
Remove the first inputStream.read() as there you read the whole filecontents already but throw it away. There is nothing more to read the second time.

Categories