Асинхронная связь с Android (клиент) и Node.js (сервер) - PullRequest
0 голосов
/ 19 мая 2018

Мне нужна связь с Android и Node.js.

Я реализовал программу, и она хорошо работает, когда они находятся в одной сети (я имею в виду тот же WIFI).Но когда я отсоединяю свой телефон Android от Wi-Fi и подключаюсь к мобильным данным, связь не получается.После поиска я обнаружил, что проблема междомена существует.Но я не могу найти решение, которое подходит к моей ситуации.Не могли бы вы помочь мне решить эту проблему?

Вот мой код на стороне сервера (server.js).

var https = require('https');
var express = require('express');
var fs = require('fs');
var app = express();
var port = 9000;
var cors = require('cors');

var welcome = "new msg from server!";

app.get('/get', function(req, res) {
    console.log('>> send new msg to client...');
    res.json(welcome);
})
app.post('/post', function(req, res) {
    console.log('<< receive new msg from client...');
    var info_from_client;
    req.on('data', function(data) {
        info_from_client = JSON.parse(data);
    })
    req.on('end', function(data) {
        var log_temp = "contents : \nname = " + info_from_client.user_name +          "\nfinger_print = " + info_from_client.finger_print;
    console.log(log_temp);
    res.write(log_temp);
    res.end();
    })
})

app.listen(port, function() {
    console.log('now server is starting...');
})

А вот мой код на стороне клиента.

public class SendToServer extends AsyncTask<String, String, String> {

private TextView tv;
private int action;
private int get = 1;
private int post = 2;


public SendToServer (TextView tv, int action) {
    this.tv = tv;
    this.action = action;
}

public String get_action(HttpURLConnection connection) {

    InputStream stream;
    BufferedReader reader = null;
    StringBuffer buffer;

    try {
        connection.connect();

        stream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(stream));
        buffer = new StringBuffer();
        String line = "";

        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        return buffer.toString();
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {

            if (reader != null) {
                reader.close();
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }//end of finally

    return null;

}
public String post_action(HttpURLConnection connection) {

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject.accumulate("user_name", "Na Jun Yeop");
        jsonObject.accumulate("finger_print", "12388452218");
    } catch (JSONException e) {
        e.printStackTrace();
    }


    OutputStream outputStream;
    InputStream inputStream;
    BufferedWriter writer = null;
    BufferedReader reader = null;
    StringBuffer buffer;

    try {
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Cache-Control", "no-cache");
        connection.setRequestProperty("Content-Type", "application/json");
        connection.setRequestProperty("Accept", "text/html");
        connection.setDoOutput(true);
        connection.setDoInput(true);
        connection.connect();

        outputStream = connection.getOutputStream();
        writer = new BufferedWriter(new OutputStreamWriter(outputStream));

        writer.write(jsonObject.toString());
        writer.flush();
        writer.close();

        inputStream = connection.getInputStream();
        reader = new BufferedReader(new InputStreamReader(inputStream));
        buffer = new StringBuffer();
        String line = "";

        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        return buffer.toString();
    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {

            if (reader != null) {
                reader.close();
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }//end of finally

    return null;
}

@Override
protected String doInBackground(String... strings) {

    HttpURLConnection connection = null;
    BufferedReader reader = null;

    try {
        URL url = new URL(strings[0]);
        connection = (HttpURLConnection)url.openConnection();

        if (action == get) {
            return get_action(connection);
        }
        else if (action == post) {
            return post_action(connection);
        }

        connection.connect();

        InputStream stream = connection.getInputStream();

        reader = new BufferedReader(new InputStreamReader(stream));

        StringBuffer buffer = new StringBuffer();

        String line = "";

        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        return buffer.toString();


    }
    catch (MalformedURLException e) {
        e.printStackTrace();
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (connection != null) {
            connection.disconnect();
        }
        try {

            if (reader != null) {
                reader.close();
            }

        }
        catch (Exception e) {
            e.printStackTrace();
        }
    }//end of finally


    return null;
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);
    tv.setText(result);
}

1 Ответ

0 голосов
/ 19 мая 2018

Чтобы решить эту проблему, вам нужно запустить сервер Node.js с SSL-сертификатом или защищенным https.Для локального тестирования, вы должны попробовать только с той же локальной сетью.Попробуйте обновить следующие параметры в вашем запросе и посмотрите, работает ли он

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: POST, GET, PUT, OPTIONS
Access-Control-Allow-Headers: Content-Type
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...