Problem regarding receiving files from android device into the esp8266 - android

I've been working on a project where i would send a file from the android app i wrote to my esp8266; the esp8266 then will write the file onto the SD card. but when esp receives the file for example a .jpg, it's all garbled and noisy.
and if i receive a .txt file it will always add a (¬í ur [B¬óøTà xp ¬) at the beginning, regardless of what method i use.
Here's my android code:
(Server thread)
Socket mySocket = null;
ServerSocket serverSocket = null;
class ServerThread implements Runnable{
int serverPort;
public ServerThread(int serverPort){
this.serverPort = serverPort;
}
#Override
public void run() {
try {
serverSocket = new ServerSocket(serverPort);
mySocket = serverSocket.accept();
output = new PrintWriter(mySocket.getOutputStream());
input = new BufferedReader(new InputStreamReader(mySocket.getInputStream()));
Log.i("connection", "server");
runOnUiThread(new Runnable() {
#Override
public void run() {
connection_state = true;
LinearLayout.LayoutParams textParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
TextView thisText = new TextView(MainActivity.this);
thisText.setId(append);
thisText.setText("Server port: " + 8080 + " ... A client just made connection");
thisText.setTextSize(20);
thisText.setBackgroundColor(Color.rgb(25, 24, 24));
thisText.setTextColor(Color.rgb(0, 100, 0));
append++;
thisText.setGravity(20);
thisText.setLayoutParams(textParams);
myTexts.addView(thisText);
}
});
new Thread(new ReceiveStringThread()).start();
} catch (IOException e) {
e.printStackTrace();
Log.i("connection", "couldn't establish connection");
} finally {
try {
if (socket != null)
socket.close();
if (serverSocket != null)
serverSocket.close();
}catch (IOException e){
e.getStackTrace();
}
}
}
}
Send file thread:
class SendFileThread implements Runnable{
String filePath;
SendFileThread(String filePath) {
this.filePath = filePath;
}
#Override
public void run() {
if(connection_state) {
File findFile = new File(filePath);
byte[] sendIt = new byte[(int) findFile.length()];
try {
BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));
bufferFile.read(sendIt, 0, sendIt.length);
ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
oos.writeObject(sendIt);
oos.flush();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
(int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.getStackTrace();
}finally {
try {
mySocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
and here's my arduino code for esp8266:
#include <ESP8266WiFi.h>
#include <SD.h>
#ifndef STASSID
#define STASSID "ESP_CLIENT"
#define STAPSK "client-1234"
#endif
const char* ssid = STASSID;
const char* password = STAPSK;
const char* host = "192.168.1.103";
const uint16_t port = 8080;
boolean connectionStatus = false;
byte buffer_array[10] = {'0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00', '0x00'};
int num_read;
WiFiClient client;
void setup() {
Serial.begin(57600);
//.................Initiate SD card................//
if(!SD.begin(SS)){
Serial.println("SD card initialization failed!");
return;
}else{
Serial.println("SD card initialized successfully");
}
Serial.println();
Serial.println();
Serial.print("Connecting to ");
Serial.println(ssid);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.println("IP address: ");
Serial.println(WiFi.localIP());
}
char *printBytes(byte *bytes) {
char bytesStr[10];
sprintf(bytesStr, "%02X", *bytes);
Serial.print("byte: ");
Serial.println(bytesStr);
return bytesStr;
}
void loop() {
if(!connectionStatus){
Serial.print("connecting to ");
Serial.print(host);
Serial.print(':');
Serial.println(port);
if (!client.connect(host, port)) {
Serial.println("********************************************Connection failed************************************************");
connectionStatus = false;
delay(1000);
return;
}else{
Serial.println("********************************************Connection established with server***********************************************");
connectionStatus = true;
}
Serial.println("sending data to server");
if (client.connected()) {
client.println("hello from ESP8266");
}
}
if(client.available()){
Serial.println("Receiving...");
num_read = client.readBytesUntil('\n',buffer_array, 10);
Serial.println("bytes read: " + (String)num_read);
printBytes(buffer_array);
File appendSD = SD.open("/testESP32.txt", FILE_WRITE);
if(!appendSD){
Serial.println("not found");
return;
}else{
Serial.println("Writing byte to file...");
appendSD.write(buffer_array, num_read);
appendSD.close();
}
}
}
and regardless of which mode i put them into, whether it'll be esp as server and android device as client or reverse, it won't make a difference at all.
anyone knows how to fix this?
i modified the SendFileThread as below but it only worked for sending .txt files correctly. but sending image files like .jpg problem still stands.
class SendFileThread implements Runnable{
String filePath;
SendFileThread(String filePath) {
this.filePath = filePath;
}
#Override
public void run() {
if(connection_state) {
File findFile = new File(filePath);
byte[] sendIt = new byte[(int) findFile.length()];
try {
BufferedInputStream bufferFile = new BufferedInputStream(new FileInputStream(findFile));
bufferFile.read(sendIt, 0, sendIt.length);
OutputStream os= mySocket.getOutputStream();
os.write(sendIt);
os.flush();
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "File was sent successfully. size: " +
(int) findFile.length() + " bytes", Toast.LENGTH_SHORT).show();
}
});
} catch (IOException e) {
e.getStackTrace();
}finally {
try {
mySocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}else{
}
}
}
and i wanna be able to send all kinds of data like .pdf .doxs as well and ObjectOutputStream sends all this kinds of files just fine if although i'm sending them to another android phone not esp8266

SOLVED: i used
client.read(buffer_array, 10);
for image files instead of
client.readBytesUntil('\n', buffer_array, 10);
and in android changed
ObjectOutputStream oos = new ObjectOutputStream(mySocket.getOutputStream());
oos.writeObject(sendIt);
to
OutputStream os= mySocket.getOutputStream();
os.write(sendIt);
and it finally worked for all types of files!

Related

(EDITED) Android peer to peer Wifi Direct Image Receiving issue

I am connecting two devices using p2p wifi direct. I have successfully sent a text message from one device to another but when it comes to sending an image I'm stuck. I tried to encode the image and decode on another side but right now the image is being sent successfully, however on the receiving end it doesn't show any image but the specific folder is being created, but when I open the image through the File Manager, it says "File format not supported" and the image doesn't open. The image has a size of 2.92KB.
One more thing I want to ask is how can I send to specific device, I've tried to put the receiving device's Inet address but it doesn't work for me.
Here is my code
For server side
public class ServerClass extends Thread {
Socket socket;
ServerSocket serverSocket;
#Override
public void run() {
try {
serverSocket = new ServerSocket(8888);
socket = serverSocket.accept();
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class SendReceive extends Thread {
private Socket socket;
private InputStream inputStream;
private OutputStream outputStream;
private DataInputStream dataInputStream;
int length;
byte[] Bbytes;
public SendReceive(Socket sckt) {
socket = sckt;
try {
inputStream = socket.getInputStream();
outputStream = socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
int bytes;
while (socket != null) {
try {
dataInputStream=new DataInputStream(inputStream);
length=dataInputStream.readInt();
Bbytes=new byte[length];
dataInputStream.readFully(Bbytes,0,Bbytes.length);
bytes = inputStream.read(Bbytes);
handler.obtainMessage(MESSAGE_READ, bytes, -1,
Bbytes).sendToTarget();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//sending images
public void writeImageData(byte[] bytes){
try {
DataOutputStream dataOutputStream=new
DataOutputStream(outputStream);
dataOutputStream.writeInt(bytes.length);
dataOutputStream.write(bytes, 0, bytes.length);
}catch (IOException e) {
e.printStackTrace();
}
}
}
The client side
public class ClientClass extends Thread {
Socket socket;
String hostAdd;
public ClientClass(InetAddress hostAddress) {
hostAdd = hostAddress.getHostAddress();
socket = new Socket();
}
#Override
public void run() {
try {
socket.connect(new InetSocketAddress(hostAdd, 8888), 700);
sendReceive = new SendReceive(socket);
sendReceive.start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
To send image to client and I am getting this toast as successful
public class SendImageClient extends AsyncTask<byte[], Void, Void> {
#Override
protected Void doInBackground(byte[]... voids) {
try {
sendReceive.writeImageData(voids[0]);
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(MainActivity.this, "Image sent",
Toast.LENGTH_SHORT).show();
}
});
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The handler for receive message and reading it
Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(#NonNull Message msg) {
switch (msg.what) {
case MESSAGE_READ:
byte[] readBuff = (byte[]) msg.obj;
Bitmap bitmap=
BitmapFactory.decodeByteArray(readBuff,0,readBuff.length);
imageView22.setImageBitmap(bitmap);
saveImage(bitmap);
break;
}
return true;
}
});
//to save image in device
private void saveImage(Bitmap finalBitmap){
String root= Environment.getExternalStorageDirectory().toString();
File myDir= new File(root+"/saved_images");
myDir.mkdirs();
Random generator= new Random();
int n=10000;
n=generator.nextInt(n);
String fname="Image-"+n+".jpg";
File file=new File(myDir,fname);
if(file.exists()){
file.delete();
}
try {
FileOutputStream out=new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 100,out);
out.flush();
out.close();
Toast.makeText(this, "image saved ", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Lastly the send button
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawable = (BitmapDrawable) imageView.getDrawable();
bitmap = drawable.getBitmap();
imageView.setImageBitmap(bitmap);
ByteArrayOutputStream byteArrayOutputStream = new
ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 0, byteArrayOutputStream);
byte[] array = byteArrayOutputStream.toByteArray();
SendImageClient sendImageClient = new SendImageClient();
sendImageClient.execute(array);
}
});
I'd appreciate any suggestions. Thank you in advance.

Wifi Direct Server/Client Connection

I am composing a WiFi Direct android app following guide of Google Developer's guide. I am just beginning to learn. I am stuck in sending an image from Client to Server. The following is Client and Server coding taken from Demo:
This is a code to call Client Intent (MainActivity):
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode ==SELECT_IMAGE) {
Log.d(MainActivity.TAG, "onActivityResult Start");
Log.d(MainActivity.TAG, "requestCode "+requestCode);
Uri uri = data.getData();
Intent serviceIntent = new Intent(this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
Log.d(MainActivity.TAG, "file path " + uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_ADDRESS, IP_SERVER);
serviceIntent.putExtra(FileTransferService.EXTRAS_PORT, PORT);
this.startService(serviceIntent);
} else {
Log.d(MainActivity.TAG, "Service transfer failed");
}
}
This is code for Client (I used IntentService in a separate class):
public class FileTransferService extends IntentService {
public static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.moon.android.wifidirectproject_moon.action.SEND_FILE";
public static final String EXTRAS_ADDRESS = "go_host";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_PORT = "go_port";
Socket socket = new Socket();
public FileTransferService() {
super("FileTransferService");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_ADDRESS);
int port = intent.getExtras().getInt(EXTRAS_PORT);
try {
Log.d(MainActivity.TAG, "Opening client socket - ");
Log.d(MainActivity.TAG, "fileUri" + fileUri);
Log.d(MainActivity.TAG, "host" + host);
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
Log.d(MainActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
Log.d(MainActivity.TAG, "is - " + is);
} catch (FileNotFoundException e) {
Log.d(MainActivity.TAG, e.toString());
}
copyFile(is, stream);
Log.d(MainActivity.TAG, "Client: Data written");
} catch (IOException e) {
Log.e(MainActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(MainActivity.TAG, e.toString());
return false;
}
return true;
}
}
This is a call to Server Intent
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
if (info.groupFormed && info.isGroupOwner) {
InetAddress groupOwnerAddress = info.groupOwnerAddress;
ownerIP = groupOwnerAddress.getHostAddress();
Log.d(MainActivity.TAG, "Owner connected" + ownerIP);
Intent serverIntent = new Intent(mActivity, ServerService.class);
serverIntent.putExtra("port",MainActivity.PORT);
mActivity.startService(serverIntent);
.....
The following is Server Intent Service:
public class ServerService extends IntentService {
public static String mClientIP;
public ServerService() {
super("ServerService");
}
#Override
protected void onHandleIntent(Intent intent) {
Context context = getApplicationContext();
Integer port = intent.getExtras().getInt("port");
try {
ServerSocket serverSocket = new ServerSocket(port);
Socket client = serverSocket.accept();
Log.d(MainActivity.TAG, "Server: Socket opened");
Log.d(MainActivity.TAG, "clientIP" + client.getInetAddress().toString());
mClientIP = client.getInetAddress().toString();
Log.d(MainActivity.TAG, "Server: connection done");
/*
*************I am stuck here******************************
*/
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
Log.d(MainActivity.TAG, "server: copying files " + f.toString());
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
} catch (IOException e) {
Log.e(MainActivity.TAG, e.getMessage());
} finally {
stopSelf();
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
} catch (IOException e) {
Log.d(MainActivity.TAG, e.toString());
return false;
}
return true;
}
}
Lastly, the following is my LogCat. I put asterisk marks where no further progress is made in Server.
1) Server device (Initial State)
: search start
: WiFi_enabled
: Owner connected192.168.49.1
2) Client Device(sending image):
...............................
Opening client socket -
: fileUricontent://media/external/images/media/16871
: host192.168.49.1
: Client socket - true
: WiFi_enabled
: is - android.os.ParcelFileDescriptor$AutoCloseInputStream#3c520d34
3) Again Server Device
: Server: Socket opened
: clientIP/192.168.49.133
: Server: connection done
: open failed: ENOENT (No such file or directory)
I must confess that I don't fully understand the server/client. I just have rough knowledge. However, if you give me any hint on what I am wrong with, I will try to learn more for myself. I've spent several days working on it but couldn't work it out. Thanks for reading this post.

Android: StreamProxy not working on Nexus4/5 with Android 5.x

Here is a source of StreamProxy I used for my project
public class StreamProxy implements Runnable {
private static final String LOG_TAG = "Stream proxy: %s";
private int port = 0;
private boolean isRunning = true;
private ServerSocket socket;
private Thread thread;
public StreamProxy() {
init();
start();
}
public int getPort() {
return port;
}
public String getProxyUrl(String uri, String tag) {
return String.format("http://127.0.0.1:%d/%s", getPort(), uri);
}
private void init() {
try {
socket = new ServerSocket(port, 0, InetAddress.getByAddress(new byte[]{127, 0, 0, 1}));
socket.setSoTimeout(5000);
port = socket.getLocalPort();
Timber.d(LOG_TAG, "port " + port + " obtained");
} catch (IOException e) {
Timber.e(e, "Error initializing server");
}
}
private void start() {
if (socket == null) {
throw new IllegalStateException("Cannot start proxy; it has not been initialized.");
}
thread = new Thread(this);
thread.start();
}
public void stop() {
isRunning = false;
if (thread == null) {
throw new IllegalStateException("Cannot stop proxy; it has not been started.");
}
thread.interrupt();
try {
thread.join(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
#Override
public void run() {
Timber.d(LOG_TAG, "running");
while (isRunning) {
try {
Socket client = socket.accept();
if (client == null) {
continue;
}
Timber.d(LOG_TAG, "client connected");
client.setKeepAlive(false);
readRequest(client);
} catch (SocketTimeoutException e) {
} catch (IOException e) {
Timber.e(e, "Error connecting to client");
}
}
Timber.d(LOG_TAG, "Proxy interrupted. Shutting down.");
}
#Nullable
private void readRequest(Socket client) throws IOException {
InputStream is;
String firstLine;
try {
is = client.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
firstLine = reader.readLine();
} catch (IOException e) {
Timber.e(LOG_TAG, "Error parsing request", e);
return;
}
if (firstLine == null) {
Timber.i(LOG_TAG, "Proxy client closed connection without a request.");
return;
}
StringTokenizer st = new StringTokenizer(firstLine);
st.nextToken();
String uri = st.nextToken().substring(1);
Timber.d(LOG_TAG, uri);
processRequest(client, uri, "");
}
#Nullable
private HttpURLConnection download(String path) throws IOException {
URL url = new URL(path);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
throw new IOException("Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage());
}
return connection;
}
private void processRequest(Socket client, String url, String tag)
throws IllegalStateException, IOException {
Timber.d(LOG_TAG, "processing");
HttpURLConnection realResponse = download(url);
if (realResponse == null) {
return;
}
InputStream data = realResponse.getInputStream();
socketWriter.setClient(client);
try {
int readBytes;
Timber.d(LOG_TAG, "writing data to client");
// Start streaming content.
byte[] buff = new byte[1024 * 8];
while (isRunning && (readBytes = data.read(buff)) != -1) {
client.getOutputStream().write(buff, 0, readBytes)
}
Timber.d(LOG_TAG, "end writing data");
} catch (IOException e) {
Timber.e(e, "Error data transfer to client");
} finally {
Timber.d(LOG_TAG, "finally block");
if (data != null) {
data.close();
}
}
}
}
It works perfectly on Android <5.0 but on Android 5.0.+ I have following error with using MediaExtractor(http://developer.android.com/reference/android/media/MediaExtractor.html)
NuCachedSource2﹕ source returned error -1, 10 retries left
NuCachedSource2﹕ source returned error -1, 9 retries left
...
And no error messages when using Mediaplayer just few quiet retries.
Maybe for Android 5 there is another way for audio streaming with caching?
Stream proxy working well actually. All errors I get from MediaExtractor was about m4a container. For most files packed in m4a format, there is no way to play it via stream by using components from Android SDK. Except some roms on Samsung, LG and some other manufactures that has this feature.

Communicating android and windows through socket

I want to make my android app open socket to my windows console app and they communicate with each other. The socket is opened and data is sent and received in windows app, but my android app does not receive the answer which sent by windows. I watch the packets in my android and I saw the packets are coming but I do not know why my app do not receive it!
windows app server class:
class Server
{
private TcpListener tcpListener;
private Thread listenThread;
public Server()
{
Console.WriteLine("\nStarting server...");
this.tcpListener = new TcpListener(IPAddress.Any, 1234);
this.listenThread = new Thread(new ThreadStart(ListenForClients));
this.listenThread.Start();
}
private void ListenForClients()
{
Console.WriteLine("\nWaiting for clients to connect...");
this.tcpListener.Start();
while (true)
{
//blocks until a client has connected to the server
TcpClient client = this.tcpListener.AcceptTcpClient();
//create a thread to handle communication with connected client
Thread clientThread = new Thread(new ParameterizedThreadStart(HandleClientComm));
clientThread.Start(client);
}
}
private void HandleClientComm(object client)
{
Console.WriteLine("\nIncoming from client...");
TcpClient tcpClient = (TcpClient)client;
NetworkStream clientStream = tcpClient.GetStream();
byte[] message = new byte[4096];
int bytesRead;
try
{
while (true)
{
bytesRead = 0;
try
{
//blocks until a client sends a message
bytesRead = clientStream.Read(message, 0, 4096);
}
catch
{
//a socket error has occured
break;
}
if (bytesRead == 0)
{
//the client has disconnected from the server
break;
}
//message has successfully been received
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("\nReceived: \n\n" + encoder.GetString(message, 0, bytesRead));
//By FMR
string response = "random responsive: " + new Random().Next(1000).ToString() + "\n";//"\r\n";
//writeData(clientStream, response);
byte[] msg = System.Text.Encoding.ASCII.GetBytes(response);
// Send back a response.
clientStream.Write(msg, 0, msg.Length);
clientStream.Flush();
Console.WriteLine("\nResponed ..." + response);
}
}
catch (Exception ex)
{
Console.WriteLine("\nException while: " + ex.Message);
}
tcpClient.Close();
}
}
my android thread:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
Socket socket = null;
ServerSocket serverSocket = null;
Boolean bRun = true;
try {
socket = new Socket(ip, port);
if(outputStream == null) {
outputStream = new DataOutputStream(socket.getOutputStream());
}
// become server
serverSocket = new ServerSocket(port);
Log.i(G.TAG, "before serverSocket.accept");
socket = serverSocket.accept();
Log.i(G.TAG, "response recieve: ");
inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}
catch (Exception e) {
try {
serverSocket.close();
} catch (IOException e1) {
Log.e(G.TAG, "serverSocket.close() e: " + e1.getMessage());
}
try {
socket.close();
} catch (IOException e1) {
Log.e(G.TAG, "socket.close() e: " + e1.getMessage());
}
}
Log.i(G.TAG, "after start recieve: ");
while (bRun) {
try {
Log.i(G.TAG, "while start: ");
String message = inputStream.readLine();
Log.i(G.TAG, "response message: " + message);
if (message != null) {
setListMessage(false, message);
}
}
catch (IOException e) {
bRun = false;
Log.e(G.TAG, "while bRun e: " + e.getMessage());
}
}
}
});
thread.start();
// in another function, my message is sent successfully from android and receive in windows
I found the problem, this line
socket = serverSocket.accept();
made the problem when I comment the line, the android app received the response!
Does anybody know why?

I have to restart my Java socket connection for multiple file transfer

I have created a small server client program for Android. It is working like charm except one thing. First session of file transfer works without any problem, but when I try to send another file, I can't do it without restarting my socket connection. I wanted to achieve this:
1. Start Android server
2. Connect remote client
3. Transfer as many files as one wishes in the same session (without having to restart server and reconnecting client)
How can it be done? Any help would be appreciated!
Here's my code snippet:
Server side methods:
public void initializeServer() {
try {
serverSocket = new ServerSocket(4444);
runOnUiThread( new Runnable() {
#Override
public void run() {
registerLog("Server started successfully at: "+ getLocalIpAddress());
registerLog("Listening on port: 4444");
registerLog("Waiting for client request . . .");
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("Listen failed", "Couldn't listen to port 4444");
}
try {
socket = serverSocket.accept();
runOnUiThread( new Runnable() {
#Override
public void run() {
registerLog("Client connected: "+socket.getInetAddress());
}
});
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.d("Acceptance failed", "Couldn't accept client socket connection");
}
}
Sending file to client:
public void sendFileDOS() throws FileNotFoundException {
runOnUiThread( new Runnable() {
#Override
public void run() {
registerLog("Sending. . . Please wait. . .");
}
});
final long startTime = System.currentTimeMillis();
final File myFile= new File(filePath); //sdcard/DCIM.JPG
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
DataInputStream dis = new DataInputStream(bis);
try {
dis.readFully(mybytearray, 0, mybytearray.length);
OutputStream os = socket.getOutputStream();
//Sending file name and file size to the server
DataOutputStream dos = new DataOutputStream(os);
dos.writeUTF(myFile.getName());
dos.writeLong(mybytearray.length);
dos.write(mybytearray, 0, mybytearray.length);
dos.flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
runOnUiThread( new Runnable() {
#Override
public void run() {
long estimatedTime = (System.currentTimeMillis() - startTime)/1000;
registerLog("File successfully sent");
registerLog("File size: "+myFile.length()/1000+" KBytes");
registerLog("Elapsed time: "+estimatedTime+" sec. (approx)");
registerLog("Server stopped. Please restart for another session.");
}
});
}
Client side (running on PC):
public class myFileClient {
final static String servAdd="10.142.198.127";
static String filename=null;
static Socket socket = null;
static Boolean flag=true;
/**
* #param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
initializeClient();
receiveDOS();
}
public static void initializeClient () throws IOException {
InetAddress serverIP=InetAddress.getByName(servAdd);
socket=new Socket(serverIP, 4444);
}
public static void receiveDOS() {
int bytesRead;
InputStream in;
int bufferSize=0;
try {
bufferSize=socket.getReceiveBufferSize();
in=socket.getInputStream();
DataInputStream clientData = new DataInputStream(in);
String fileName = clientData.readUTF();
System.out.println(fileName);
OutputStream output = new FileOutputStream("//home//evinish//Documents//Android//Received files//"+ fileName);
long size = clientData.readLong();
byte[] buffer = new byte[bufferSize];
while (size > 0
&& (bytesRead = clientData.read(buffer, 0,
(int) Math.min(buffer.length, size))) != -1) {
output.write(buffer, 0, bytesRead);
size -= bytesRead;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Try flushing just after
output.write(buffer, 0, bytesRead);
If this still doesn't work I found mine server/client works best with objectoutputstreams that you use in the the following way.
oos = new ObjectOutputStream(socket.getOutputStream());
ois = new ObjectInputStream(socket.getInputStream());
// always call flush and reset after sending anything
oos.writeObject(server.getPartyMembersNames());
oos.flush();
oos.reset();
YourObject blah = (YourObject) ois.readObject();

Categories

Resources