When clients are connected to the server they should be able to send images to server, so the server can display the received images. I have used an AsyncTask at the server-end to do the task.
when one client is connected to the server everything seems fine, images are receiving from that client but when the next client connected it's not working, sometimes the first client gets disconnected or the images are not receiving from one client or both.
Can someone help me with this? am i doing anything wrong?
Server-end AsyncTask
public static class FileServerAsyncTask extends AsyncTask {
private Context context;
private TextView statusText;
public FileServerAsyncTask(Context context, View statusText) {
this.context = context;
this.statusText = (TextView) statusText;
}
@Override
protected String doInBackground(Void... params) {
class ClientWorker implements Runnable {
private Socket client;
private final File f;
//Constructor
ClientWorker(Socket client, File f) {
this.client = client;
this.f = f;
}
public void run(){
try{
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));
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
}
try {
ServerSocket serverSocket = new ServerSocket(8988);
Log.d(WiFiDirectActivity.TAG, "Server: Socket opened");
boolean check = true;
while(check){
ClientWorker w;
try{
//server.accept returns a client connection
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
w = new ClientWorker(serverSocket.accept(),f);
Thread t = new Thread(w);
t.start();
return f.getAbsolutePath();
} catch (IOException e) {
System.out.println("Accept failed: 4444");
System.exit(-1);
}
}
serverSocket.close();
return null;
} catch (IOException e) {
Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
@Override
protected void onPostExecute(String result) {
if (result != null) {
statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
@Override
protected void onPreExecute() {
statusText.setText("Opening a server socket");
}
}
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(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}