Ayham Showa
Ayham Showa

Reputation: 135

Android Studio socket server and client send and recieve data

I'm newer programer in android .. I need help to sending text between two phone by wifi first : server second :client I'm searching more but i need Simple code and easy to help me thnx for advance

Upvotes: 1

Views: 8657

Answers (1)

אביב פישר
אביב פישר

Reputation: 115

I guess sockets is what you are looking for...

  • To create a socket in android the socket must be created in a thread.

Client side example:

    private final String IP = "9.9.9.9";
    private final int PORT = 8080;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

    class MainThread implements Runnable {

        @Override
        public void run() {

            try {
                InetAddress address = InetAddress.getByName(IP);
                socket = new Socket(address,PORT);
                new Thread(new GetThread()).start();
            } catch (UnknownHostException e1){
                e1.printStackTrace();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }

    class GetThread implements Runnable {

        @Override
        public void run() {

            try {
                InputStreamReader isR=new InputStreamReader(socket.getInputStream());
                BufferedReader bfr=new BufferedReader(isR);
                while(true) {
                    String textMessage = bfr.readLine();
                    // TODO: Insert logic which use the recived message (textMessage)
                    }
                }

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

In the thread, the socket is waiting for data to be sent (while(true)).

and the IP is the ip of the server (if you are connecting to your computer

with wifi, you should check your ip address with ipconfig in the command line).

Upvotes: 1

Related Questions