android-socket.io未连接

1szpjjfi  于 2021-07-07  发布在  Java
关注(0)|答案(1)|浏览(429)

我使用java和socket.io连接到我的服务器,但是我尝试从android客户端连接nodejs服务器,但是连接没有成功(onconnector)我尝试了所有的解决方案,但我不知道我的问题是什么。
我的服务器代码(server.js);

const express = require('express');
    const app = express();
    const path = require('path');
    const server = require('http').createServer(app);
    const io = require('socket.io')(server);
    const port = process.env.PORT || 3000;

    server.listen(port, () => {
      console.log('Server listening at port %d', port);
    });

    app.use(express.static(path.join(__dirname, 'public')));

    io.on('connection', (socket) => {
      let addedUser = false;
      console.log('connection success');

      socket.on('example', (data) => {
        socket.emit('example', 'example');
        console.log('example');
      });

      socket.on('disconnect', () => {

        console.log('disconnecting');

      });
    });

在java端,我对清单使用internet和http权限。

<uses-permission android:name="android.permission.INTERNET" />
    <application
        android:usesCleartextTraffic="true"...

我的java代码;

public class MainActivity extends AppCompatActivity {
  private static final String TAG = MainActivity.class.getName();

  public static Socket mSocket; {
    try {
      mSocket = IO.socket("http://192.168.1.35:3000");
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
    mSocket.connect();
  }

  private Emitter.Listener onConnectError = new Emitter.Listener() {
    @Override
    public void call(Object...args) {
      runOnUiThread(new Runnable() {
        @Override
        public void run() {
          Toast.makeText(getApplicationContext(), "Unable to connect to NodeJS server", Toast.LENGTH_LONG).show();

        }
      });
    }
  };

  @Override
  protected void onDestroy() {
    super.onDestroy();

    mSocket.disconnect();
    mSocket.off(Socket.EVENT_CONNECT_ERROR, onConnectError);
    mSocket.off(Socket.EVENT_CONNECT_TIMEOUT, onConnectError);
  }
}
yqlxgs2m

yqlxgs2m1#

我想你得用 ws://192.168.1.35:3000" .
所以改变这个

public static Socket mSocket; {
    try {
      mSocket = IO.socket("http://192.168.1.35:3000");
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }

为了这个

public static Socket mSocket; {
    try {
      mSocket = IO.socket("ws://192.168.1.35:3000");
    } catch (URISyntaxException e) {
      throw new RuntimeException(e);
    }
  }

相关问题