Reputation: 17
I have written a socket-based Android-to-server app for sending images. Here is what I have succeed with so far: the socket is connecting, the image is being sent, but that's it. It remains being sent and I see the file on my server-side with 0kb, and the sending never ends.
I'm sending a 233kb JPEG image over it.
Here is the client side:
public class AccountCreator extends Activity {
private String serverIpAddress = "10.0.2.2";
private boolean connected = false;
private Handler handler = new Handler();
private Socket socket;
private Button sendimage;
//private ImageView profile;
private byte [] imgbyte;
String filepath;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mes_registerpage);
sendimage = (Button) findViewById(R.id.sendpic);
ImageView imv = (ImageView)findViewById(R.id.imageView1);
sendimage.setOnClickListener(connectListener);
filepath = "storage/sdcard/autumn.jpg";
File imagefile = new File(filepath);
FileInputStream fis = null;
try {
fis = new FileInputStream(imagefile);
} catch (FileNotFoundException e) {
System.out.println("file not found");
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(fis);
imgbyte = getBytesFromBitmap(bm);
imv.setImageBitmap(bm);
}
private OnClickListener connectListener = new OnClickListener() {
@Override
public void onClick(View v) {
if (!connected) {
// serverIpAddress = serverIp.getText().toString();
// if (!serverIpAddress.equals(""))
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
};
public class ClientThread implements Runnable {
public void run() {
try {
// InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
socket = new Socket(serverIpAddress,1500);
connected = true;
while (connected==true) {
try {
/*File myFile = new File (filepath);
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 = socket.getOutputStream();
Log.d("ClientActivity", "C: Sending command.");
//System.out.println("Sending...");
os.write(mybytearray,0,mybytearray.length);
os.flush();*/
Log.d("ClientActivity", "C: Sending command.");
/*PrintWriter out = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(socket
.getOutputStream())), true);*/
// WHERE YOU ISSUE THE COMMANDS
OutputStream output = socket.getOutputStream();
Log.d("ClientActivity", "C: image writing.");
output.write(imgbyte);
output.flush();
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
protected void onStop() {
super.onStop();
try {
// MAKE SURE YOU CLOSE THE SOCKET UPON EXITING
socket.close();
connected = false;
} catch (IOException e) {
e.printStackTrace();
}
}
public byte[] getBytesFromBitmap(Bitmap bitmap) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.JPEG, 70, stream);
return stream.toByteArray();
}
}
And here is the server code:
public Server(int port) {
this(port, null);
}
public Server(int port, ServerGUI sg) {
this.sg = sg;
this.port = port;
sdf = new SimpleDateFormat("HH:mm:ss");
al = new ArrayList<ClientThread>();
}
public void start() throws InterruptedException {
keepGoing = true;
try
{
// the socket used by the server
ServerSocket serverSocket = new ServerSocket(port);
// infinite loop to wait for connections
while(keepGoing)
{
// format message saying we are waiting
display("Server waiting for Clients on port " + port +
".");
Socket socket = serverSocket.accept();
// if I was asked to stop
if(!keepGoing)
break;
ClientThread t = new ClientThread(socket);
jobdone=false;
al.add(t);
t.start();
}
// I was asked to stop
try {
serverSocket.close();
for(int i = 0; i < al.size(); ++i) {
ClientThread tc = al.get(i);
try {
tc.sInput.close();
tc.sOutput.close();
tc.socket.close();
}
catch(IOException ioE) {
// not much I can do
}
}
}
catch(Exception e) {
display("Exception closing the server and clients: " + e);
}
}
// something went bad
catch (IOException e) {
String msg = sdf.format(new Date()) + " Exception on new ServerSocket: " + e +
"\n";
display(msg);
}
}
/*
* For the GUI to stop the server
*/
protected void stop() {
keepGoing = false;
// connect to myself as Client to exit statement
// Socket socket = serverSocket.accept();
try {
new Socket("10.0.2.2",1500);
}
catch(Exception e) {
// nothing I can really do
}
}
/*
* Display an event (not a message) to the console or the GUI
*/
private void display(String msg) {
String time = sdf.format(new Date()) + " " + msg;
if(sg == null)
System.out.println(time);
else
sg.appendEvent(time + "\n");
}
// create a server object and start it
public static void shutdown() {
jobdone = true;
}
/** One instance of this thread will run for each client */
class ClientThread extends Thread {
// the socket where to listen/talk
String Type;
Socket socket;
InputStream sInput;
ObjectOutputStream sOutput;
// my unique id (easier for deconnection)
int id;
// Constructore
ClientThread(Socket socket) throws InterruptedException, IOException {
// a unique id
id = ++uniqueId;
this.socket = socket;
/* Creating both Data Stream */
System.out.println("Thread trying to create Object Input/Output
Streams");
// create output first
int bytesRead;
int current = 0;
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
try {
InputStream is = socket.getInputStream();
System.out.println("receiving");
FileOutputStream fos = new FileOutputStream("D://IMG-
20130112-WA0011.jpeg");
// destination path and name of file
BufferedOutputStream bos = new BufferedOutputStream(fos);
bytesRead = is.read(mybytearray2,0,mybytearray2.length);
current = bytesRead;
try {
bytesRead =
is.read(mybytearray2, current,
(mybytearray2.length-current));
if(bytesRead >= 0)
{current += bytesRead;
}
while(bytesRead > -1);
{
bos.write(mybytearray2, 0 , current);
bos.flush();
long end = System.currentTimeMillis();
//System.out.println(end-start);
bos.close();
}
}finally{
}
}finally{
}
}
}
// what will run forever
// remove myself from the arrayList containing the list of the
// connected Clients
public void main(String[] args) throws InterruptedException {
// start server on port 1500 unless a PortNumber is specified
int portNumber = 1500;
switch(args.length) {
case 1:
try {
portNumber = Integer.parseInt(args[0]);
}
catch(Exception e) {
System.out.println("Invalid port number.");
System.out.println("Usage is: > java
Server [portNumber]");
return;
}
case 0:
break;
default:
System.out.println("Usage is: > java Server
[portNumber]");
return;
}
// create a server object and start it
Server server = new Server(portNumber);
server.start();
}
}
Do you guys know what is wrong?
Upvotes: 0
Views: 299
Reputation: 11214
int filesize=65383;
byte [] mybytearray2 = new byte [filesize];
You don't know the filesize at forehand. Moreover you send a file of 233kB and trying to read all in mybytearray2 will give you a bufferoverflow and your server will crash. By the way: from where did you get/copy this code? I saw it before. I'ts no good.
Upvotes: 1