简体   繁体   中英

how do i write on server and read on android

i want to create a printwriter in my java server and a buffertreader in my android code. right know i can send a message from my android and read it on my java compiler but i want to do the oppsite aswell. read on android and write on server. do i need two applications for that because i dont know if i can just put it in between try i each code?

android code:

try {

 client = new Socket("10.0.2.2", 4444);  //connect to server
 printwriter = new PrintWriter(client.getOutputStream(),true);
 printwriter.write(messsage);  //write the message to output stream

 printwriter.flush();
 printwriter.close();
 client.close();   //closing the connection

} catch (UnknownHostException e) {

java server:

    while (true) {
        try {

            clientSocket = serverSocket.accept();   //accept the client connection
            inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
            bufferedReader = new BufferedReader(inputStreamReader); //get the client message
            message = bufferedReader.readLine();

            System.out.println(message);
            inputStreamReader.close();
            clientSocket.close();

        } catch (IOException ex) {

thank you for taking your time to read my problem

Yes you can create two way communication between them, all you have to do is open an InputStream on the client side (Android) and Open an OutputStream on the Java Server Side, it can be achieved in the following manner:

android code:

try {

 client = new Socket("10.0.2.2", 4444);  //connect to server
 printwriter = new PrintWriter(client.getOutputStream(),true);
 printwriter.write(messsage);  //write the message to output stream

 printwriter.flush();
 printwriter.close();

 InputStream in = client.getInputStream();

 byte data[] = new byte[1024]
 in.read(data);    ///perform your reading operation here


 client.close();   //closing the connection

} catch (UnknownHostException e) {

java server:

while (true) {
    try {

        clientSocket = serverSocket.accept();   //accept the client connection
        inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
        bufferedReader = new BufferedReader(inputStreamReader); //get the client message
        message = bufferedReader.readLine();

        System.out.println(message);
        inputStreamReader.close();


        PrintWriter pw = new PrintWriter(clientSocket.getOutputStream());
        pw.write(new String("write data here"));
        pw.flush();
        pw.close();
        clientSocket.close();

    } catch (IOException ex) {

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM