1

I had a question, I built the server part and the client with a socket and did not receive any errors. When I type the local address in the browser, it shows the information in cmd, but when I run the Android application in the emulator or mobile, it does not connect to the server.

The permissions I used:

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

Server codes:

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');

The MainActivity.java is:

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);
    }
}

please guide me.

mz gh
  • 23
  • 3

2 Answers2

0

I had the same issue before, it is because you are running the application on a emulator. Try to run it on a local phone on your local network with the API also running.

Whisper
  • 43
  • 2
  • 5
  • I also ran the program on the phone but it did not connect to the server. – mz gh Jan 17 '21 at 20:47
  • @mzgh your post is exactly a duplicate, you can find the original post here: [link] (https://stackoverflow.com/questions/51889837/cannot-connect-to-localhost-api-from-android-app) or even better: [link](https://stackoverflow.com/questions/5806220/how-to-connect-to-my-http-localhost-web-server-from-android-emulator?noredirect=1&lq=1) – Whisper Jan 19 '21 at 19:15
0

In emulator Localhost Ip is :http://10.0.2.2 use it if u are running in localhost.

abhishek92
  • 61
  • 4