I'm trying to implement a client-server pair in Android using standard Java sockets. So far, I've successfully implemented one to one client-server connection. Now, I'm modifying my server side code to accept multiple client connection. I've taken help from here. I'm creating a serverSocket and wait for client connection in an infinite while loop. Once the client side socked is accepted, I run a new thread to handle that client and then again wait for new connection. Unfortunately, the program keeps crashing for some unknown reason! The logcat simply says- "error opening trace file: No such file or directory". The file path is correct (it was working fine in older implementation). Can anyone suggest what am I doing wrong? Is it related to missing manifest permission? Here is what I've done so far:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent launchFileManager = new Intent(getBaseContext(),
FileChooserActivity.class);
startActivityForResult(launchFileManager, REQUEST_CODE); //receives files
//fileArray has been populated here
Button btn=(Button)findViewById(R.id.dispFilesid);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
initializeServer();
}
});
}
private void initializeServer() {
boolean listening = true;
try {
serversocket = new ServerSocket(4444);
} catch (IOException e) {
e.printStackTrace();
Log.d("Listen failed", "Listening to port 4444 failed");
}
while (listening) {
try {
socket = serversocket.accept();
Thread Clienttrd = new Thread(new Runnable() {
@Override
public void run() {
try {
OutputStream myos=socket.getOutputStream();
myos.write(filepathNameArray.size()); //send file count
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (!fileArray.isEmpty()) {
for (int i = 0; i < filepathNameArray.size(); i++){
copyFile(fileArray.get(i), fileArray.get(i).getName().toString());
//mtv.setText(fileArray.get(i).getName().toString());
}
}
}
});
Clienttrd.start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The intent for FileChooserActivity returns an ArrayList containing a list of file URIs. These URIs are then wrapped around files and written over DataOutputStream of Socket object. Please help. Any insight would be appreciated! Thanks in advance!
listeningandfileArrayare not thread safe, but are potentially accessed from multiple threads, which is a recipe for trouble.