Click here to Skip to main content
15,888,293 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I had created two android applications connected with sockets. Client sends an image to server and Server displays it. when you touch the image on server, it gets its coordinates,this is working now. what I need is that server sends the coordinates to the client, but I dont know how to send them to client and retrieve them, should I open a new socket ? I have no idea how to do this. Can somebody give me a hand please?

This is my code so far

Java
///////////////////////////SERVER/////////////////////
package com.example.serverlate;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.DisplayMetrics;
import android.widget.ImageView;
import android.widget.TextView;

public class ServerLate extends Activity {

    private ServerSocket serverSocket;
    String touchedCoordinates;
    Handler updateConversationHandler;
    Thread serverThread = null;
    private ImageView imageView;
    public static final int SERVERPORT = 6000;

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_server_late);

        imageView=(ImageView) findViewById(R.id.imageViewServer);

        updateConversationHandler = new Handler();
        this.serverThread = new Thread(new ServerThread());
        this.serverThread.start();

    }

    @Override
    protected void onStop() {
        super.onStop();
        try {
            serverSocket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    class ServerThread implements Runnable {

        public void run() {
            Socket socket = null;
            try {
                serverSocket = new ServerSocket(SERVERPORT);
            } catch (IOException e) {
                e.printStackTrace();
            }
            while (!Thread.currentThread().isInterrupted()) {

                try {

                    socket = serverSocket.accept();
                    CommunicationThread commThread = new CommunicationThread(socket);
                    new Thread(commThread).start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    class CommunicationThread implements Runnable {

        private Socket clientSocket;
        private DataInputStream input;    
        public CommunicationThread(Socket clientSocket) {

            this.clientSocket = clientSocket;

            try {
                InputStream in = this.clientSocket.getInputStream();
                this.input = new DataInputStream(in);               
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void run() {
            while (!Thread.currentThread().isInterrupted()) {
                try {
                    byte[] data;
                    int len= this.input.readInt();                  
                    data = new byte[len];                   
                    if (len > 0) {
                        this.input.readFully(data,0,data.length);
                    }   
                    updateConversationHandler.post(new updateUIThread(data));
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }

    }

    class updateUIThread implements Runnable {
        private byte[] byteArray;

        public updateUIThread(byte[] array){    
            this.byteArray=array;   
        }

        @Override
        public void run() { 
            Bitmap bitmap = BitmapFactory.decodeByteArray(byteArray , 0, byteArray .length);
            imageView.setImageBitmap(bitmap);
            imageView.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                touchedCoordinates="Touch coordinates : " +
                        String.valueOf(event.getX()) + " x " + String.valueOf(event.getY());
                    return true;
            }
        });
        }
    }
}


Java
/////////////////////CLIENT///////////////////////////////
package com.example.clientlate;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

public class ClientLate extends Activity {

    private Socket socket;

    private static final int SERVERPORT = 5000;
    private static final String SERVER_IP = "10.0.2.2";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_client_late);      

        new Thread(new ClientThread()).start();
    }

    public void onClick(View view) {
        try {           
            ImageView imageView=(ImageView) findViewById(R.id.imageView1);
            Bitmap bmp=((BitmapDrawable)imageView.getDrawable()).getBitmap(); 

            ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
            bmp.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos); 
            byte[] array = bos.toByteArray();

            OutputStream out = socket.getOutputStream(); 
            DataOutputStream dos = new DataOutputStream(out);
            dos.writeInt(array.length);
            dos.write(array, 0, array.length);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    class ClientThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress serverAddr = InetAddress.getByName(SERVER_IP);

                socket = new Socket(serverAddr, SERVERPORT);

            } catch (UnknownHostException e1) {
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }

        }

    }
}


Posted

With TCP, there is absolutely no difference where how sending data is directed: from client to server or from server to client. The connection is always established by the initiative of the client, which is connected to the listening server, and this is the only reason why a client is a client and a server is a server. After connection, client and server part can exchange data in both directions, only the order of these operations should be matching, which is established by one or another application-layer protocol you use over TCP (which is the transport-level protocol:
http://en.wikipedia.org/wiki/Application_layer[^],
http://en.wikipedia.org/wiki/Transport_layer[^],
http://en.wikipedia.org/wiki/Transmission_Control_Protocol[^].

I want to emphasize that such application-layer protocol always exist, even if you think you don't have any; in this case, such protocol still exist, implicitly defined by your code. Naturally, it's more productive to admit its existence and define it more explicitly. Now, some may think that such protocol works as follows: the client connects, sends one or more requests; and the server side responds to each request. Even though this is the case in many cases, like HTML, this is absolutely not a law. Your protocol can be anything else.

Besides, you can have two different TCP sessions between the same client and the same service. A server can listen on two ports, and each client can connect and establish two separate connections. For one pair of sockets (client and server sockets), the protocol can allow a client to send requests and the server should respond; on second on, the server always requests and the client responds. At the first client request, the client can pass the server some kind of identification, so the server could create an association between two client sockets, as the sockets "of the same logical client". This is just a very simple example of the operations. In reality, you will be limited only by two things 1) TCP protocol, 2) your fantasy.

For some more ideas, please take a look at my past answers (related to TCP but unrelated to Java and Android):
an amateur question in socket programming[^],
Multple clients from same port Number[^].

Good luck,
—SA
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900