client.getInputStream returns null - java

I am trying to use the WifiDirect demo api to send a recorded audio to another android device but input stream from the socket always returns null.
Any help is much appreciated.
Here are portion of the code
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
Socket client = serverSocket.accept();
Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory(), File.separator + "SuDAB/received/"
+ "sudab-" + System.currentTimeMillis()
+ ".3gp");
File dirs = new File(f.getParent());
if (!dirs.exists()) {
dirs.mkdirs();
}
f.createNewFile();
Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
and
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime = System.currentTimeMillis();
if (inputStream == null) {
return false;
}
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime = System.currentTimeMillis() - startTime;
Log.v(WiFiDirectActivity.TAG, "Time taken to transfer all bytes is : " + endTime);
} catch (IOException e) {
Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
this is how i pass the file to be sent to the FileTransferService
mContentView.findViewById(R.id.btn_start_client).setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
// Allow user to pick an image from Gallery or other
// registered apps
TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
statusText.setText("Sending: " + lastFile);
Log.d(WiFiDirectActivity.TAG, "Intent----------- " + lastFile);
Intent serviceIntent = new Intent(getActivity(), FileTransferService.class);
Log.d(WiFiDirectActivity.TAG, "File transfer service created...");
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, lastFile);
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
getActivity().startService(serviceIntent);
}
});

serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, lastFile);
should be
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, "file://"+lastFile);
instead.

Related

Unable to Unzip file when downloaded from URL, but works when downloaded from FTP

I am trying to download an e-book from URL and unzip it, which further goes for display. While the same unzip logic works perfectly for a FTP download, when it comes to URL, unzipping method does nothing after download.
My book download calling method :
DownloadBook db = new DownloadBook(localFile,"some url",book.key,context,(TaskListener) result -> {
if (result) {
runOnUiThread(() -> pBar.setVisibility(View.VISIBLE));
Runnable t = (Runnable) () -> {
unzip(localFile.getPath(), b.key.replace(".zip",""), b);
isDownloaded = true;
//Deleting downlaoded zip file
System.out.println("zip file deleted - "+localFile.delete());
String urls = localFile.getPath() + "/" + ((b.key).replace(".zip", ""));
System.out.println("URL IS " + urls);
System.out.println("Going for Display");
GlobalVars.title = b.title;
Intent intent = new Intent(My_Library.this, DisplayActivity.class);
startActivity(intent);//
};
t.run();
} else {
runOnUiThread(() ->
{
alert = new AlertDialog.Builder(this);
alert.setTitle("Error");
alert.setMessage("Could not download. Please try again !")
.setCancelable(true)
.setNegativeButton("Continue", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(My_Library.this, My_Library.class);
startActivity(intent);
dialog.cancel();
}
});
alert.create();
alert.show();
}
);
}
});
The zip file download method :
t = new Thread(new Runnable() {
#Override
public void run() {
InputStream input = null;
OutputStream output = null;
HttpURLConnection connection = null;
try {
URL url = new URL("some url");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream(localFile);
byte data[] = new byte[4096];
long total = 0;
int count;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
System.out.println("Total is "+total);
if(fileLength>0)
{
System.out.println("File length is "+fileLength+" local file length is "+localFile.length());
percent = (int) (total * 100 / fileLength);
System.out.println("FTP_DOWNLOAD bytesTransferred /downloaded -> " + percent);
mProgress.setProgress(percent);
}
output.write(count);
output.flush();
}
mListener.finished(true);
} catch (Exception e) {
e.printStackTrace();
mListener.finished(false);
} finally {
try {
output.flush();
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
connection.disconnect();
}
The unzip method
public void unzip(String _zipFile, String _targetLocation, Book b) {
pBar.setVisibility(View.VISIBLE);
GlobalVars.path = _targetLocation;
_targetLocation = getApplicationContext().getFilesDir().getPath();
dirChecker(_targetLocation);
try {
BufferedInputStream fin = new BufferedInputStream(new FileInputStream(_zipFile));
ZipInputStream zin = new ZipInputStream(fin);
ZipEntry ze = null;
while ((ze = zin.getNextEntry()) != null) {
System.out.println("Unzipping file -> " + ze.getName());
//create dir if required while unzipping
if (ze.isDirectory()) {
dirChecker(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
} else {
File f = new File(getApplicationContext().getFilesDir().getPath() + "/" + ze.getName());
dirChecker(f.getParent());
long size = f.length();
BufferedOutputStream fout = new BufferedOutputStream(new FileOutputStream(new File(String.valueOf(f.getAbsoluteFile()))));
byte[] buffer = new byte[1024];
int read = 0;
while ((read = zin.read(buffer)) != -1) {
fout.write(buffer, 0, read);
}
zin.closeEntry();
fout.close();
}
zin.close();
} catch (Exception e) {
System.out.println(e);
}
}
The FTP download class method Unzip works absolutely fine. But as I try to put download from url, it just downloads but not unzips.
You have to change the output buffer writing method.
So instead of, in zip download method
output.write(count);
Use,
output.write(data,0,count);

UDP with sequence numbers

I am trying to implement a Reliable UDP protocol for a class assignment in Java. I have managed to add the acknowledgments to every datagram packet that is received, but I am having trouble implementing Sequence Numbers in the datagram packets that I am sending.
Can anyone suggest an easy method to implement this?
#EJP I have tried implementing what you just suggested. This is my code till now (its still very raw - i was using hit and try method to implement it)
Server side
public class TestServer extends Activity {
private DatagramSocket serverSocket;
Thread serverThread = null;
byte[] incomingData;
byte[] outgoingData;
//int numBytesRead = 0;
int ackSent = 0;
int numPackRecv = 0;
int BUF_SIZE = 1024;
String msg = "ACK";
BufferedInputStream data=null;
BufferedOutputStream out =null;
public static final int SERVERPORT = 6000;
String outputFile = "/sdcard/Movies/asddcopy.mp4";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_server);
this.serverThread = new Thread(new ServerThread());
this.serverThread.start();
}
#Override
protected void onStop() {
super.onStop();
try {
serverSocket.close();
} catch (Exception e) {
Log.d("SERVER", "Inside onStop()");
Log.d("SERVER", Log.getStackTraceString(e));
}
}
class ServerThread implements Runnable {
#SuppressLint("NewApi")
public void run() {
try {
serverSocket = new DatagramSocket(SERVERPORT);
incomingData = new byte[BUF_SIZE];
//outgoingData = new byte[512];
outgoingData = msg.getBytes();
long startRxPackets = TrafficStats.getUidRxPackets(Process.myUid());
long startTime = System.nanoTime();
out = new BufferedOutputStream(new FileOutputStream(outputFile, true));
while (!Thread.currentThread().isInterrupted()) {
//serverSocket.setSoTimeout(5000);
while (true) {
try{
//DatagramPacket incomingPacket = new DatagramPacket(incomingData, incomingData.length);
DatagramPacket incomingPacket = new DatagramPacket(incomingData, BUF_SIZE);
serverSocket.receive(incomingPacket);
byte[] data = incomingPacket.getData();
//out.write(data,0,incomingPacket.getLength());
//String msg = new String(incomingPacket.getData());
ByteArrayInputStream in = new ByteArrayInputStream(data);
ObjectInputStream is = new ObjectInputStream(in);
if (is == null) {
is = new ObjectInputStream(in);
}
Message msg = (Message) is.readObject();
System.out.println(msg.getSeqNo());
/*if ("END".equals(msg.substring(0, 3).trim())) {
Log.d("SERVER", "Inside END condition");
break;
}*/
out.write(msg.getData(),0,msg.getData().length);
numPackRecv += 1;
Log.d("SERVER", "Packet Received: " + numPackRecv);
InetAddress client = incomingPacket.getAddress();
int client_port = incomingPacket.getPort();
DatagramPacket outgoingPacket = new DatagramPacket(outgoingData, outgoingData.length, client, client_port);
serverSocket.send(outgoingPacket);
ackSent += 1;
//Log.d("SERVER","Packet Received: " + numPackRecv + " :: " + "Ack Sent: " + ackSent);
}catch(Exception e) {
Log.d("SERVER", "Inside run() ex1");
Log.d("SERVER", Log.getStackTraceString(e));
break;
}
}
out.close();
serverSocket.disconnect();
serverSocket.close();
Log.d("SERVER", "Transfer Complete");
Log.d("SERVER", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("SERVER", "Total Packets Received = " + Long.toString(TrafficStats.getUidRxPackets(Process.myUid()) - startRxPackets));
Log.d("SERVER", "Packets Received from Socket = " + numPackRecv);
break;
}
out.close();
serverSocket.disconnect();
serverSocket.close();
/* Log.d("SERVER", "Transfer Complete");
Log.d("SERVER", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("SERVER", "Total Packets Received = " + Long.toString(TrafficStats.getUidRxPackets(Process.myUid()) - startRxPackets));
Log.d("SERVER", "Packets Received from Socket = " + numPackRecv);*/
}catch (Exception e) {
Log.d("SERVER", "Inside run() ex2");
Log.d("SERVER", Log.getStackTraceString(e));
serverSocket.disconnect();
serverSocket.close();
}
}
}
This is the Client side
public class TestClient extends Activity { private DatagramSocket clientSocket;
byte[] incomingData;
int BUF_SIZE = 500;
int numBytesRead = 0;
int numPackSent = 0;
private static final int SERVERPORT = 6000;
private static final String SERVER_IP = "10.0.0.22";
String inFile = "/sdcard/Movies/asdd.mp4";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_client);
new Thread(new ClientThread()).start();
}
public void onClick(View view) {
new workInProgress().execute("");
}
private class workInProgress extends AsyncTask<Object, Object, Object> {
#SuppressLint("NewApi")
#Override
protected Object doInBackground(Object... params) {
try {
Log.d("CLIENT", "Sending a file to the server...");
BufferedInputStream inputBuf = new BufferedInputStream(new FileInputStream(inFile));
//byte[] fileBytes = new byte[(int) inFile.length()];
byte[] fileBytes = new byte[BUF_SIZE];
incomingData = new byte[BUF_SIZE];
double numPktToSend = Math.ceil(inFile.length()*1.0/BUF_SIZE);
//Log.d("CLIENT", "Total packets to be sent = " + numPktToSend);
int sleepCycle = 1;
long sysPackSent = 0;
//long startTxPackets = TrafficStats.getTotalTxPackets();
long startTxPackets = TrafficStats.getUidTxPackets(Process.myUid());
Log.d("CLIENT", "startTxPacks: " + startTxPackets);
long packDrops = 0;
long startTime = System.nanoTime();
long count=0;
long ackRec=0;
int seqNo = 0;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(outStream);
while((numBytesRead = inputBuf.read(fileBytes)) != -1) {
//DatagramPacket packet = new DatagramPacket(fileBytes, fileBytes.length);
if (os == null) {
os = new ObjectOutputStream(outStream);
}
Message msg = new Message(++seqNo, fileBytes, false);
os.writeObject(msg);
os.flush();
os.reset();
byte[] data = outStream.toByteArray();
DatagramPacket packet = new DatagramPacket(data, data.length);
clientSocket.send(packet);
numPackSent += 1;
//Log.d("CLIENT", "No of packets sent = " + numPackSent);
sysPackSent = TrafficStats.getUidTxPackets(Process.myUid()) - startTxPackets;
try{
clientSocket.setSoTimeout(5000);
packet = new DatagramPacket(incomingData, incomingData.length);
clientSocket.receive(packet);
String recAck = new String(packet.getData());
ackRec++;
}
catch(Exception e) {
//Log.d("CLIENT", Log.getStackTraceString(e));
}
packDrops = numPackSent - ackRec;
if (packDrops > count) {
sleepCycle = Math.min(16, sleepCycle * 2);
count = packDrops;
Log.d("CLIENT",String.valueOf(sleepCycle) + " :: " + numPackSent);
} else {
sleepCycle = Math.max(sleepCycle - 1, 1);
}
Thread.sleep(sleepCycle);
}
if (numBytesRead == -1) {
fileBytes = "END".getBytes();
Log.d("CLIENT", "Sending END Packet");
clientSocket.send(new DatagramPacket(fileBytes, fileBytes.length));
}
Log.d("CLIENT", "Actual Time elapsed = " + (System.nanoTime() - startTime)/Math.pow(10, 9) + " s");
Log.d("CLIENT", "Total Packets Transmitted = " + Long.toString(sysPackSent));
Log.d("CLIENT", "No of packets dropped = " + String.valueOf(packDrops));
Log.d("CLIENT", "Packets Pushed to Socket = " + numPackSent);
Log.d("CLIENT", "Number of Acknoledgments received " +ackRec);
inputBuf.close();
os.close();
outStream.close();
clientSocket.disconnect();
clientSocket.close();
Log.d("CLIENT", "Sending file.. Complete!!!");
} catch (Exception e) {
Log.d("CLIENT", Log.getStackTraceString(e));
clientSocket.disconnect();
clientSocket.close();
}
return null;
}
}
class ClientThread implements Runnable {
#Override
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
clientSocket = new DatagramSocket();
clientSocket.connect(serverAddr, SERVERPORT);
Log.d("CLIENT", "Connection Successful");
} catch (UnknownHostException e1) {
Log.d("CLIENT", "Inside run() UnknownHostEx");
Log.d("CLIENT", Log.getStackTraceString(e1));
} catch (IOException e1) {
Log.d("CLIENT", "Inside run() IOEx");
Log.d("CLIENT", Log.getStackTraceString(e1));
}
}
}
I am getting a few errors at the Server side:
I am receiving the same sequence number for each packet (i.e. 1)
I am not sure about the buffer size for the incoming packet, as I am using 500 bytes at Client side and 1024 at the Sever. And if I take 500 bytes in both the codes I get a End of File exception.
I would really appreciate if you could suggest better ways to implement the same thing!
Thanks :)
Thanks!
Create a ByteArrayOutputStream.
Wrap it in a DataOutputStream
Use DataOutputStream.writeInt() to write the sequence number.
Use write() to write the data.
Construct the DatagramPacket from the byte array returned by the ByteArrayOutputStream.
At the receiver, do exactly the reverse, using the complementary classes and methods in each case. What those are is left as an exercise for the reader.
The simplest method would probably be to a look at the TCP protocol, and stick all the TCP headers into the start of each of your UDP packets.

copying to another apps unprotected storage Android

I'm trying to wirte files to the internal storage actually to an other apps unprotected storage the code I'm using works it just doesn't work when I want to copy to /android/data/com.some.app can this be done or do I have to make the app use root access
Thanks
public class tools extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tools);
}
public void installflat(View view)
{ Toast.makeText(tools.this, "This could take a long time", Toast.LENGTH_LONG).show();
File direct = new File(Environment.getExternalStorageDirectory() + "/android" + "/data" + "/com.some.app" +"/");
if (!direct.exists())
{
if (direct.mkdir())
{ //directory is created;
}}
installflat_pt2();
Toast.makeText(tools.this, "try it now", Toast.LENGTH_LONG).show();
}
private void installflat_pt2()
{
AssetManager assetManager = getAssets();
String[] files = null;
try
{
files = assetManager.list("tools");
}
catch (IOException e)
{
Log.e("tag", e.getMessage());
}
for (String filename : files)
{
System.out.println("File name => " + filename);
InputStream in = null;
OutputStream out = null;
try
{
in = assetManager.open("tools/" + filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream(Environment.getExternalStorageDirectory().toString() + "/android" + "/data" + "/com.some.app" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch (Exception e)
{
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}

Sockets, sent pdf file always arrives zero bytes size

I'm sending a pdf file from android tablet client to Java app running on Windows 7. The file always arrives as a size of zero bytes. what is the problem here?
Before the pdf file was sent from client to server, the size of the file as long value is sent from client to server, this size is correct and always arrives to the server. For the pdf file, I'm using for this test the size is 566718 bytes.
How can I get the pdf file to arrive as the correct size?
Server code
public class Server {
ServerSocket serverSocket;
Socket socket;
boolean runner = true;
Server() throws IOException{
serverRunner();
System.out.println("server constructor started");
} // Server() constructor
public void serverRunner() throws IOException {
System.out.println("serverrunner started");
try {
serverSocket = new ServerSocket(6789, 100);
runner = true;
while (runner) {
socket = serverSocket.accept();
MultiThreader multi = new MultiThreader(socket);
Thread t = new Thread(multi);
t.start();
} // while runner
} catch (IOException ex) {
}
} // serverRunner()
} // class Server
public class MultiThreader implements Runnable {
Socket socket;
public int fileSizeFromClient;
FileOutputStream fos = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
DataInputStream dis = null;
DataOutputStream dos = null;
public MultiThreader(Socket socket){
System.out.println("print out from multithreader class");
this.socket = socket;
} // multiThreader
#Override
public void run() {
System.out.println("multi threader started");
// action #1 read file from client =====================================
// transfer.pdf read this file sent from android device to this computer
int bufferSize = 0;
try {
bis = new BufferedInputStream(socket.getInputStream());
dis = new DataInputStream(bis);
fileSizeFromClient = dis.readInt();
System.out.println("file size from client is " + fileSizeFromClient);
File fileDirectory = new File("C:/DOWNLOAD/");
if (!fileDirectory.exists()) {
fileDirectory.mkdir();
}
File file = new File("C:/DOWNLOAD/transfer.pdf");
file.createNewFile();
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos);
dos = new DataOutputStream(bos);
byte[] buffer = new byte[fileSizeFromClient];
int totalBytesRead = 0;
while(totalBytesRead < fileSizeFromClient){
int bytesRemaining = fileSizeFromClient = totalBytesRead;
int bytesRead = dis.read(buffer, 0, (int) Math.min(buffer.length, bytesRemaining));
if(bytesRead == -1) {
break;
} else {
dos.write(buffer, 0, bytesRead);
totalBytesRead += bytesRead;
}
} // while
} catch (IOException ex) {
Logger.getLogger(MultiThreader.class.getName()).log(Level.SEVERE, null, ex);
} finally {
try {
// socket.close();
} catch (IOException ex) {
Logger.getLogger(MultiThreader.class.getName()).log(Level.SEVERE, null, ex);
}
}
} // run
} // MultiThreader
client code
public class MainActivity extends Activity implements Runnable {
TextView textViewOne;
Button buttonOne;
Socket socket;
private String serverIP = "192.XXX.X.X";
FileInputStream fis;
FileOutputStream fos;
private File file;
DataInputStream dis;
DataOutputStream dos;
BufferedInputStream bis;
BufferedOutputStream bos;
long length;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewOne = (TextView) findViewById(R.id.textView1);
buttonOne = (Button) findViewById(R.id.button1);
buttonOne.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Thread myThread = new Thread(MainActivity.this);
myThread.start();
}
});
} // oncreate
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
textViewOne.setText("run method started");
}
});
try {
socket = new Socket(InetAddress.getByName(serverIP), 6789);
if (socket == null) {
return;
} else {
MainActivity.this.runOnUiThread(new Runnable(){
#Override
public void run() {
textViewOne.setText("connected");
}
});
}
file = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "transfer.pdf");
length = file.length();
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
bos = new BufferedOutputStream(socket.getOutputStream());
dos = new DataOutputStream(bos);
dos.writeInt((int) length); // sends the length as number bytes is file size
int count = 0;
byte[] buffer = new byte[(int) length];
while ((count = bis.read(buffer)) > 0)
{
bos.write(buffer, 0, count);
}
bos.flush();
bis.close();
socket.close();
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} // mainactivity
This is the problem, I believe.
int bytesRemaining = fileSizeFromClient = totalBytesRead;
That's doing two assignments, so you're assigning 0 to fileSizeFromClient immediately, and exiting the loop.
You meant:
int bytesRemaining = fileSizeFromClient - totalBytesRead;
That's a pretty subtle typo, and you were unlucky that it's a typo which still resulted in valid code :(
Given that you're closing the socket immediately anyway though, it's not clear why you're sending the file size first. Your code could be simpler if you just had the same "copy from an input stream to an output stream until the input runs out of data" at both the client and the server, just from a FileInputStream to a Socket's OutputStream at the client, and the Socket's InputStream to a FileOutputStream (possibly with a buffering wrapper) at the server.
I'd also recommend closing all streams - if you're using Java 7, you can do this simply using a try-with-resources statement; in earlier versions you should close streams in finally blocks.
- By rule of thumb, always close the Streams after writing/reading to and from it.
- Close the Stream at Server side.
- Use Socket with InputStream and Scanner for hassle free data transfer between socket. (Thats what i felt, experimenting with sockets.)

send image from android java to c# server on pc

i'm trying to send image from android to C# server using Socket, but something goes wrong.
package com.example.clientsocket;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
TextView serverMessage;
Thread m_objThreadClient;
Socket clientSocket;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serverMessage=(TextView)findViewById(R.id.textView1);
}
public void Start(View view)
{
m_objThreadClient=new Thread(new Runnable()
{
public void run()
{
try
{
clientSocket= new Socket("192.168.88.113",2001);
//ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
File myFile = new File("/storage/sdcard0/Pictures/CameraSample/*.jpg");
InputStream fis = new FileInputStream("/storage/sdcard0/Pictures/CameraSample/*.jpg");
byte [] buffer = new byte[(int)myFile.length()];
fis.read(buffer,0,buffer.length);
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(buffer.length);
outputStream.write(buffer,0,buffer.length);
outputStream.flush();
outputStream.close();
clientSocket.close();
//byte [] buffer = new byte[(int)myFile.length()];
// ...
//fis.read(buffer,0,buffer.length);
//OutputStream os = clientSocket.getOutputStream();
//oos.writeObject("37");
//oos.flush();
//oos.writeObject(buffer);
//os.write(37);
//os.write(buffer);
// <- This one.
/*
int temp = 0 ;
while((temp = fis.read(buffer)) != -1)
{
outputStream.write(buffer, 0, temp);
} */
/*
Message serverMessage= Message.obtain();
ObjectInputStream ois =new ObjectInputStream(clientSocket.getInputStream());
String strMessage = (String)ois.readObject();
serverMessage.obj=strMessage;
mHandler.sendMessage(serverMessage);
oos.close();
ois.close();*/
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
m_objThreadClient.start();
}
Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg)
{
messageDisplay(msg.obj.toString());
}
};
public void messageDisplay(String servermessage)
{
serverMessage.setText(""+servermessage);
}
}
Server gets 60800 as buffer length every single image that I send, and I can't make an image on C# using this array.
I want than to receive char array from server on android.
Am I doing something wrong in the JPG file, because I want to have only one image at the same time in my folder?
This is my sample C# client socket send image to Android Server. In my sending side, I send Image size first and follow by image bytes. Hope it helps.
C# Client
try
{
// IPAddress[] ipAddress = Dns.GetHostAddresses("192.168.173.129");
IPAddress[] ipAddress = Dns.GetHostAddresses("192.168.1.32");
IPEndPoint ipEnd = new IPEndPoint(ipAddress[0], 4800);
string file=#"C:\Users\test\Desktop\send image\test\abc.jpg
{
// Create Socket to send
Socket senderSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
senderSocket.Connect(ipEnd);
//send picture name
// Connect the socket to the remote endpoint. Catch any errors.
FileInfo FileInfo = new FileInfo(file);
byte[] data = new byte[8];
String fInfoStr = FileInfo.Length.ToString();
while (fInfoStr.Length < 8)
{
fInfoStr = "0" + fInfoStr;
}
byte[] countBuf = Encoding.ASCII.GetBytes(fInfoStr);
byte[] fBuffer = new byte[FileInfo.Length];
//FileStream
FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read);
//Read byte from image
fs.Read(fBuffer, 0, fBuffer.Length);
fs.Flush();
fs.Close();
senderSocket.Send(fBuffer, 0, fBuffer.Length, SocketFlags.None);
senderSocket.Close();
lblTestMsg.Visible = true;
lblErrorMsg.Visible = false;
lblTestMsg.Text = "File Sent Successfully";
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
Android Server
Socket socket = serverSocket.accept();
InputStream iStream = socket.getInputStream(); ;
String currentDateandTime = sdf.format(new Date());
// int filenamelen =iStream.read();
//image Name
byte[] countBuf = new byte[8];
// byte[] imageNameByte = new byte[7];
iStream.read(countBuf);
//iStream.read(imageNameByte,0,7);
readTxt = new String(countBuf);
// imageName= new String(imageNameByte);
int size = Integer.parseInt(readTxt);
//Send byte array
senderSocket.Send(countBuf, 0, data.Length, SocketFlags.None);new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName).mkdirs();
Log.e("TCP", "Create Drkt");
//Create Image(File)
new File(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName, imageName + ".jpg").createNewFile();
Log.e("TCP", "Create Img");
try {
FileOutputStream fOutputStream = new FileOutputStream(Environment.getExternalStorageDirectory() + File.separator + "DCIM" + File.separator + "SPARCS" + File.separator + folderName + File.separator + fileName + File.separator + imageName + ".jpg");
BufferedOutputStream BufOutputStream = new BufferedOutputStream(fOutputStream);
byte[] aByte = new byte[size];
int byteRead;
// int bytesRead = iStream.read(aByte);
//Read from server
while ((byteRead = iStream.read(aByte)) > 0) {
Log.e("TCP", "Save to file");//Write to file
BufOutputStream.write(aByte, 0, byteRead);
}
publishProgress();
notifyID++;
// String imageUri =Environment.getExternalStorageDirectory() + File.separator + "myDirectory" + File.separator + readTxt + File.separator+currentDateandTime+".jpg";
BufOutputStream.flush();
BufOutputStream.close();
socket.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
} catch (Exception e) {
Log.e("TCP", "C: Error", e);
}
You have a mistake in this code:
byte [] buffer = new byte[(int)myFile.length()];
fis.read(buffer,0,buffer.length);
OutputStream outputStream = clientSocket.getOutputStream();
outputStream.write(buffer.length); // You are changing the image here...
outputStream.write(buffer,0,buffer.length);
You are sending wrong data on the Socket, and you may run on out of memory if image is to big. Also you are converting myFile.length() to int. There is a reason for files length to be long. It allow very large files to be scanned. May be it doesn't meter in your case but I suggest not doing this.
It should be some thing like this:
byte [] buffer = new byte[1048];
OutputStream outputStream = clientSocket.getOutputStream();
int numberOfBytesBeenRead = fis.read(buffer,0,buffer.length);
while(numberOfBytesBeenRead != -1){
outputStream.write(buffer,0,numberOfBytesBeenRead);
numberOfBytesBeenRead = fis.read(buffer,0,buffer.length);
}

Categories

Resources