I'm trying to revise my android code which can only send string originally. The task is to let it can transfer pictures. I know there are so many different ways to implement this. But I tried and really don't know why my pictures cant be sent, although there is no problem with the connecting. Is there anyone who can tell me? I will be really appreciate it. I'm just a beginner, Please forget my poor programming skill.
Here is the main part of server below
private Runnable socket_server = new Runnable(){
public void run(){
handler.post(new Runnable() {
public void run() {
test.setText("Listening...." + getMyIp());
}
});
try{
serverSocket = new ServerSocket(1234);
while (true) {
Socket client = serverSocket.accept();
handler.post(new Runnable() {
public void run() {
test.setText("Connected.");
}
});
try {
File myFile = new File ("/sdcard/DCIM/img2.jpg");
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 = client.getOutputStream();
os.write(mybytearray,0,mybytearray.length);
os.flush();
client.close();
test.setText("Received.");
} catch (Exception e) {
handler.post(new Runnable() {
public void run() {
test.setText("Sending erro");
}
});
}
}
}catch(IOException e){
handler.post(new Runnable() {
public void run() {
test.setText("Fail to buitl the socket");
}
});
}
}
};
and here is part of client
new Thread()
{
@Override
public void run() {
// TODO Auto-generated method stub
InetAddress serverAddr = null;
SocketAddress sc_add = null;
Socket socket = null;
try
{
serverAddr = InetAddress.getByName("192.168.1.105");
sc_add= new InetSocketAddress(serverAddr,1234);
socket = new Socket();
socket.connect(sc_add,2000);
File myFile = new File("/sdcard/DCIM/img2.jpg");
InputStream fis = new FileInputStream("/sdcard/DCIM/img2.jpg");
OutputStream outputStream = socket.getOutputStream();
byte [] buffer = new byte[(int)myFile.length()];
int temp = 0 ;
while((temp = fis.read(buffer)) != -1){
outputStream.write(buffer, 0, temp);
}
outputStream.flush();
socket.close();
} catch (UnknownHostException e) {
//TextView01.setText("InetAddress fail");
} catch (SocketException e) {
//TextView01.setText("fail to develop socket");
} catch(IOException e) {
//TextView01.setText("fail to sending");
}
}
}.start();