【问题标题】:Android application does not connect to the serverAndroid 应用程序无法连接到服务器
【发布时间】:2021-04-22 01:51:19
【问题描述】:

我有一个问题,我用套接字构建了服务器部分和客户端,但没有收到任何错误。当我在浏览器中输入本地地址时,会在cmd中显示信息,但是当我在模拟器或手机中运行Android应用程序时,它并没有连接到服务器。

我使用的权限:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

服务器代码:

const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);

//app.use(express.static(__dirname + '/static')
app.get('/', function (req, res, next) {
    res.sendFile(__dirname + '/static/index.html');
});
io.on('connection', function (socket) {
    console.log('one user connected ' + socket.id);
    socket.on('message',function (data) {
        console.log(data);
        
        var sockets=io.sockets.sockets;
        sockets.forEach(function (item) {
            
            item.emit('message',{message:data});
            
        });
        
        
        
        
    });
    socket.on('disconnect', function (){
        console.log('user disconnected');
    })
    
    
});

http.listen(8000)
    console.log('server run on port 8000');

MainActivity.java 是:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.nkzawa.emitter.Emitter;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.URISyntaxException;

public class MainActivity extends AppCompatActivity {

    private Socket socket;

    {
        try {
            socket = IO.socket("http://192.168.42.51:8000");
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
    }

    Button btnSend;
    EditText edtTextMessage;
    LinearLayout linearMessage;
    LinearLayout.LayoutParams layoutParams;
    public Handler handler;


    @Override
    protected void onDestroy() {
        super.onDestroy();
        socket.disconnect();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnSend = (Button) findViewById(R.id.btnSend);
        handler =new Handler();
        edtTextMessage = (EditText) findViewById(R.id.edtTextMessage);
        linearMessage=(LinearLayout)findViewById(R.id.linearMessage);
        socket.connect();
        socket.on("message", handlerIncomingMessage);

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String message = edtTextMessage.getText().toString();
                sendMessage(message);
            }
        });
    }

    public Emitter.Listener handlerIncomingMessage = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
        handler.post(new Runnable() {
            @Override
            public void run() {
                JSONObject jsonObject=(JSONObject)args[0];
                String message="";
                try {
                    message=jsonObject.getString("message").toString();
                    TextView textView=new TextView(getApplicationContext());
                    textView.setText(message);
                    textView.setTextSize(18);
                    layoutParams=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.WRAP_CONTENT);
                    linearMessage.addView(textView);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        }
    };

    private void sendMessage(String message) {
        socket.emit("Message", message);
    }
}

请指导我。

【问题讨论】:

    标签: java android node.js server socket.io


    【解决方案1】:

    我之前也遇到过同样的问题,这是因为您在模拟器上运行应用程序。尝试在本地网络上的本地电话上运行它,同时 API 也在运行。

    【讨论】:

    • 我也在手机上运行了这个程序,但它没有连接到服务器。
    • @mzgh 您的帖子完全是重复的,您可以在此处找到原始帖子:[链接] (stackoverflow.com/questions/51889837/…) 甚至更好:link
    【解决方案2】:

    在模拟器中 localhost Ip 是 :http://10.0.2.2 如果你在 localhost 中运行,请使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-09-21
      • 1970-01-01
      • 2016-08-09
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多