当前位置: 首页 > 知识库问答 >
问题:

Android应用程序没有连接到服务器

章光华
2023-03-14

我有一个问题,我用套接字构建了服务器部分和客户机,没有收到任何错误。当我在浏览器中键入本地地址时,它会在cmd中显示信息,但当我在emulator或mobile中运行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');

Main Activity.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);
    }
}

请引导我。

共有2个答案

孔城
2023-03-14

在emulator中,本地主机Ip为:http://10.0.2.2如果您在本地主机中运行,请使用它。

谷梁凌
2023-03-14

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

 类似资料:
  • 问题内容: 我无法让我的Android应用程序连接到socket.io聊天服务器。我正在使用由Gottox创建的socket.io-java- client,可以在这里找到:https : //github.com/Gottox/socket.io-java- client 服务器在端口7000上本地运行。我使用的是Android模拟器,因此我使用的是10.0.2.2:7000来访问服务器。 任何

  • 你能帮我吗?我正在尝试创建一个Android应用程序,它将连接到SQL服务器数据库。我正在使用JDBC驱动程序和: > 在项目设置中添加了JDBC- 最后,我收到了一个例外,那就是驱动程序com。微软jdbc。未找到SQLServerDriver 如果我在Java应用程序上运行相同的控制台应用程序,它就会工作。

  • 我所有的橱柜。Service.ts 我的app.module.ts 我在控制台收到这条消息 ×执行命令'javac'时出错。确保您已经安装了Java Development Kit(JDK)并设置了JAVA_HOME环境变量。您将无法为Android构建您的项目。为了能够为Android构建,请验证您是否安装了Java Development Kit(JDK),并按照http://docs.nat

  • 命令: 给出了错误: 但是运行sudo权限,工作: 有没有可能因为sudo要求阻止我在intellij中打开数据库而放弃它?在回答这个问题时,我尝试了以下方法:不使用sudo连接到本地MySQL服务器: 这没有帮助。上面的问题抛出了一个不同的错误

  • 我的应用程序,使用套接字。io,无法连接到节点。js服务器。 服务器node.js Android应用程序: 当我连接到服务器时,服务器不会说“socket.name connected”,也不会发出事件“sensorChanged”。问题出在哪里?