无法连接到本地主机

时间:2019-01-07 14:40:54

标签: android node.js kotlin retrofit retrofit2

我是Android App开发的新手。我正在Android Studio(科特林)制作一个演示Android应用程序。我的应用程序基本上是服务器应用程序。我正在使用Retrofit作为一个库,而使用node.js作为一个后端开发,并且我没有使用任何数据库,而是使用JSON(gson Retrofit Converter)代替了Database。所以,有一个recyclerview,我想在其中获取数据,但是什么时候,我在Android手机中运行我的应用程序。它显示java.net套接字超时异常,无法连接。首先,我将127.0.0.1:9000更改为10.0.2.2:9000端口,但是什么也没有发生。它显示了同样的事情。我正在使用Windows PC。我将提供.js文件和前端代码。预先谢谢你。

//my node.js codes

var express = require('express');
var app = express();
var fs = require("fs");

var bodyParser = require('body-parser')
app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({
    extended: true
}));

//Arbitrary ID manager since we don't use a database
var index = 5;

// Initializing Destinations Array.. It will behave like a dummy database 
var destinations = [{
    "id": 1,
    "city": "Mumbai",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce accumsan quis justo quis hendrerit. Curabitur a ante neque. Fusce nec mauris sodales, auctor sem at, luctus eros. Praesent aliquam nibh neque. Duis ut suscipit justo, id consectetur orci. Curabitur ultricies nunc eu enim dignissim, sed laoreet odio blandit.",
    "country" : "India"
}, {
    "id": 2,
    "city": "Melbourne",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce accumsan quis justo quis hendrerit. Curabitur a ante neque. Fusce nec mauris sodales, auctor sem at, luctus eros. Praesent aliquam nibh neque. Duis ut suscipit justo, id consectetur orci. Curabitur ultricies nunc eu enim dignissim, sed laoreet odio blandit.",
    "country" : "Australia"
}, {
    "id": 3,
    "city": "Washington DC",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce accumsan quis justo quis hendrerit. Curabitur a ante neque. Fusce nec mauris sodales, auctor sem at, luctus eros. Praesent aliquam nibh neque. Duis ut suscipit justo, id consectetur orci. Curabitur ultricies nunc eu enim dignissim, sed laoreet odio blandit.",
    "country" : "USA"
}, {
    "id": 4,
    "city": "New Delhi",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce accumsan quis justo quis hendrerit. Curabitur a ante neque. Fusce nec mauris sodales, auctor sem at, luctus eros. Praesent aliquam nibh neque. Duis ut suscipit justo, id consectetur orci. Curabitur ultricies nunc eu enim dignissim, sed laoreet odio blandit.",
    "country" : "India"
}, {
    "id": 5,
    "city": "Tokyo",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce accumsan quis justo quis hendrerit. Curabitur a ante neque. Fusce nec mauris sodales, auctor sem at, luctus eros. Praesent aliquam nibh neque. Duis ut suscipit justo, id consectetur orci. Curabitur ultricies nunc eu enim dignissim, sed laoreet odio blandit.",
    "country" : "Japan"
}]

// A promo message to user 
var message = "Black Friday! Get 50% cachback on saving your first spot.";

app.get('/messages', function (req, res) {
    res.end(JSON.stringify(message));
})

// Get the list of destinations, convert it to JSON and send it back to client 
app.get('/destination', function (req, res) {
    var count = req.query.count != undefined ? req.query.count : req.query.count = 100;
    if(req.query.country){
        var countrySpots = destinations.filter(function(destination) {
            return destination.country == req.query.country
        });
        res.end(JSON.stringify(countrySpots.slice(0, count)));
    }
    
    res.end(JSON.stringify(destinations.slice(0, count)));
})

// Get one particular Destination using ID 
app.get('/destination/:id', function (req, res) {
    for (var i = 0; i < destinations.length; i++) {
        if(destinations[i].id == req.params.id){
            res.end(JSON.stringify(destinations[i]));
        }
    }
})

// Create a new Destination and add it to existing Destinations list 
app.post('/destination', function (req, res) {
    var newDestination = {
        "city": req.body.city,
        "description": req.body.description,
        "country" : req.body.country,
        "id": index + 1
    }

    index++;

    destinations.push(newDestination);
    res.status(201).end(JSON.stringify(newDestination));
})

// Update a Destination 
app.put('/destination/:id', function (req, res) {
    var destination;
    for (var i = 0; i < destinations.length; i++) {
        if(destinations[i].id == req.params.id){
            destinations[i].city = req.body.city;
            destinations[i].country = req.body.country;
            destinations[i].description = req.body.description;
            destination = destinations[i];
        }
    }

    res.end(JSON.stringify(destination));
})

// Delete a Destination 
app.delete('/destination/:id', function (req, res) {
    for (var i = 0; i < destinations.length; i++) {
        if(destinations[i].id == req.params.id){
            destinations.splice(i, 1);
            res.status(204).end(JSON.stringify(destinations[i]));
        }
    }
});

// Home Page 
app.get('/', (req, res) => res.send('Welcome! You are all set to go!'))

// Configure server 
var server = app.listen(9000, '127.0.0.1', function (req, res) {

    var host = server.address().address
    var port = server.address().port

    console.log(`Server running at http://${host}:${port}/`);
})

DestinationListActivity

class DestinationListActivity : AppCompatActivity() {

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_destiny_list)

    setSupportActionBar(toolbar)
    toolbar.title = title

    fab.setOnClickListener {
        val intent = Intent(this@DestinationListActivity, DestinationCreateActivity::class.java)
        startActivity(intent)
    }
}

override fun onResume() {
    super.onResume()

    loadDestinations()
}

private fun loadDestinations() {

    // To be replaced by retrofit code
    //  destiny_recycler_view.adapter = DestinationAdapter(SampleData.DESTINATIONS)

    val destination = ServiceBuilder.buildService(DestinationService::class.java)

    val requestCall = destination.getDestinationList()

    requestCall.enqueue(object : Callback<List<Destination>> {
        override fun onFailure(call: Call<List<Destination>>, t: Throwable) {
            Toast.makeText(this@DestinationListActivity , "Error Occures" + t.toString(), Toast.LENGTH_LONG).show()
        }

        override fun onResponse(call: Call<List<Destination>>, response: Response<List<Destination>>) {
            if(response.isSuccessful) {
                val destinationList = response.body()!!
                destiny_recycler_view.adapter = DestinationAdapter(destinationList)
            } else if(response.code() == 401) {
                Toast.makeText(this@DestinationListActivity, "Your session is over plz login again", Toast.LENGTH_LONG).show()
            }
            else {
                Toast.makeText(this@DestinationListActivity, "Failed to receive items", Toast.LENGTH_LONG).show()
            }
        }
    })
}

}

// ServiceBuilder类

object ServiceBuilder {

// Before release, change this URL to your live server URL such as "https://smartherd.com/"
private const val URL = "http://47.247.190.247:9000/"

// Create OkHttp Client
private val okHttp = OkHttpClient.Builder()
                                  .connectTimeout(100, TimeUnit.SECONDS)
                                  .readTimeout(100,TimeUnit.SECONDS)

// Create Retrofit Builder
private val builder = Retrofit.Builder().baseUrl(URL)
    .addConverterFactory(GsonConverterFactory.create())
    .client(okHttp.build())

// Create Retrofit Instance
private val retrofit = builder.build()

fun <T> buildService(serviceType: Class<T>): T {
    return retrofit.create(serviceType)
}

}

//接口类

interface DestinationService {

@GET("destination")
fun getDestinationList(): Call<List<Destination>>

}

It is a photo of my android phone

1 个答案:

答案 0 :(得分:0)

我找到了答案。我的本地主机未与我的android手机连接,这就是为什么它显示端口错误的原因。因此,将我的android手机连接到本地主机。我实际上使用“ ngrok”公开了我的本地主机。然后,我的数据正在加载到我的Android手机上。谢谢。