In the previous thread I had succeeded in sending file from client to server, so i'm trying to move a step further by sending file back to client. But it crashed. When googled the crash exception - though there were different answers for as many threads - a clue I pulled out was that the client code was closing the socket while the server was trying to send. So I tried commenting out the sock.close() in client code. Though it didn't crash anymore but it didn't send file data either (which is worse so I remove the comment).
So how do I solve this? Here are the Client code, server code and crash dump; I've placed an arrow to indicate line 55 pointed to by the exception
Many thanks
Client code: (to simplify you can Ignore the android part of code, its only purpose is to help select a file)
public class FSendfileActivity extends Activity {
private Socket sock;
private static final int SELECT = 1;
private String serverIP = "192.168.1.4";
private String selectedImagePath;
private ImageView img;
final static String puzzleGame= "pop";
String ImageDir2Client;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fsendfile);
ImageDir2Client = Environment.getExternalStorageDirectory().getAbsolutePath();
img = (ImageView) findViewById(R.id.ivPic);
((Button) findViewById(R.id.bBrowse)).setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult( Intent.createChooser( intent, "Select PGame Image data" ), SELECT );
}
});
Button send = (Button) findViewById(R.id.bSend);
final TextView status = (TextView) findViewById(R.id.tvStatus);
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
new Thread(new Runnable() {
@Override
public void run() {
try {
sock = new Socket();
connection(sock, serverIP, 57925);
File myFile = new File (selectedImagePath);
byte [] mybytearray = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray,0,mybytearray.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
Log.v(qcd, "mybytearray.length "+mybytearray.length);
os.flush();
sock.close(); // CLIENT CLOSE SOCKET HERE
//================= client receiving data ==============================
int filesize=2373620;
int bytesRead;
int current = 0;
byte [] mybytearray2 = new byte [filesize];
InputStream is;
Long start=0l, end=0l;
while( ((is = sock.getInputStream()) != null) || ((end-start) < 10000) ){
start = System.currentTimeMillis();
FileOutputStream fos = new FileOutputStream(ImageDir2Client + "/client RootFolder/fromServer00002.jpg"); // destination path and name of file
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
current = bytesRead;
do {
bytesRead = is.read(mybytearray2, current, (mybytearray2.length-current));
if(bytesRead >= 0) current += bytesRead;
} while(bytesRead > -1);
bos.write(mybytearray2, 0 , current);
bos.flush();
end = System.currentTimeMillis();
bos.close();
}
System.out.println("AT CLIENT:"+" time elapsed "+(end-start));
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
});
}
public static void connection(Socket s, String serverIP, int port) {
try {
Log.v(qcd, " before connecting ****...");
s.connect(new InetSocketAddress(serverIP, port), 120000);
Log.v(qcd, " socket connection DONE!! ");
} catch (UnknownHostException e) {
e.printStackTrace();
Log.v(qcd, " Unknown host..."+e);
} catch (IOException e) {
e.printStackTrace();
Log.v(qcd, " Failed to connect... "+e);
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
if (requestCode == SELECT_PICTURE) {
Uri selectedImageUri = data.getData();
selectedImagePath = getPath(selectedImageUri);
TextView path = (TextView) findViewById(R.id.tvPath);
path.setText("Image Path : " + selectedImagePath);
img.setImageURI(selectedImageUri);
Log.v(qcd, selectedImagePath);
}
}
}
public String getPath(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
}
Server code:
public class FileServer {
public static void main(String[] args) throws IOException {
int filesize=2373620; // filesize temporary hardcoded
long start = System.currentTimeMillis();
int bytesRead;
int current = 0;
InetAddress IP=InetAddress.getLocalHost();
ServerSocket servsock = new ServerSocket(57925);
System.out.println("IP "+IP.getHostAddress()+" ***%% :"+servsock.getLocalPort());
while (true) {
System.out.println("Waiting...");
Socket sock = servsock.accept();
System.out.println("Accepted connection : " + sock);
byte [] mybytearray = new byte [filesize];
InputStream is = sock.getInputStream();
FileOutputStream fos = new FileOutputStream("C:\\server RootFolder\\puzzleGame_050052z.jpg");
BufferedOutputStream 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();
long end = System.currentTimeMillis();
// System.out.println("milliseconds "+(end-start));
System.out.println("AT SERVER: bytesRead "+bytesRead+" current "+current);
bos.close();
//================== Server Processing starts here =====================================
File myFile = new File ("C:\\server RootFolder\\puzzleGame_050052z.jpg");
byte [] mybytearray2 = new byte [(int)myFile.length()];
FileInputStream fis = new FileInputStream(myFile);
BufferedInputStream bis = new BufferedInputStream(fis);
bis.read(mybytearray2,0,mybytearray2.length);
OutputStream os = sock.getOutputStream();
System.out.println("Sending to client...");
os.write(mybytearray2,0,mybytearray2.length); //<================ LINE 55
System.out.println("mybytearray2.length "+mybytearray2.length);
//================== Send Data to Client ============================================
// OutputStream out = sock.getOutputStream();
// servsock.close();
// sock.close();
}
}
}
Crash
Exception in thread "main" java.net.SocketException: Connection reset by peer: socket write error
at java.net.SocketOutputStream.socketWrite0(Native Method)
at java.net.SocketOutputStream.socketWrite(Unknown Source)
at java.net.SocketOutputStream.write(Unknown Source)
at server.FileServer.main(FileServer.java:55)