2017-06-16 78 views
0

我試圖連接到我的android應用程序中的node.js服務器。 我可以連接到網絡上的服務器只在我的應用程序中沒有。 這意味着我猜服務器工作正常。沒有在android中與socket.io連接

我用express框架創建了服務器。 這裏是我的package.json

{ 
    "name": "rt", 
    "version": "0.0.0", 
    "private": true, 
    "scripts": { 
    "start": "node ./bin/www" 
}, 

"dependencies": { 
    "body-parser": "~1.17.1", 
    "cookie-parser": "~1.4.3", 
    "debug": "~2.6.3", 
    "express": "~4.15.2", 
    "fs": "0.0.1-security", 
    "jade": "~1.11.0", 
    "morgan": "~1.8.1", 
    "oracledb": "^1.13.1", 
    "serve-favicon": "~2.4.2", 
    "socket.io": "^1.7.4" 

}}

,這裏是我的客戶端代碼。

private static final String TAG = "MainActivity"; 

private Socket socket; 
{ 
    try{ 
     socket = IO.socket("http://210.123.255.155:55555"); 
    }catch(Exception e){ 
     Log.e(TAG, e.toString()); 
    } 
} 

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

    socket.connect(); 
    Log.d(TAG, "" + socket.connected()); 
} 

我試了3個庫。

  1. com.github.nkzawa:socket.io客戶端:0.3.0
  2. io.socket:socket.io客戶端:0.8.3
  3. io.socket:engine.io客戶端: 0.8.3

當然,我更改了每個庫的mainActivity代碼。
三個都不起作用。 我的logcat總是說

D/mainActivity: false 

並沒有任何錯誤。

這個問題的任何想法?

+0

嘗試{ 插座= IO.socket( 「http://210.123.255.155:55555」) ; socket.connect(); Log.d(TAG,「」+ socket.connected()); (例外e){ } Log.e(TAG,e.toString()); } –

+0

https://socket.io/blog/native-socket-io-and-android/ –

+0

@Divyesh Patel我的代碼有什麼不同? –

回答

0

讓新類並將它命名爲你喜歡

public class ChatApplication { 
    private Socket mSocket; 
    { 
     try { 
      mSocket = IO.socket(SERVER_URL); 
     } catch (URISyntaxException e) { 
      throw new RuntimeException(e); 
     } 
    } 

    public Socket getSocket() { 
     return mSocket; 
    } 
} 
在MainActivity

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

    ChatApplication app = new ChatApplication(); 
    mSocket = app.getSocket(); 
    mSocket.on(Socket.EVENT_CONNECT_ERROR, onConnectError); 
    mSocket.on(Socket.EVENT_CONNECT_TIMEOUT, onConnectError); 
    mSocket.on(Socket.EVENT_CONNECT, onConnect); 
    mSocket.on(Socket.EVENT_DISCONNECT, onDisconnect); 
    mSocket.connect(); 
} 

public Emitter.Listener onConnect = new Emitter.Listener() { 
    @Override 
    public void call(Object... args) { 
     Log.d(TAG, "Socket Connected!"); 
    } 
}; 

private Emitter.Listener onConnectError = new Emitter.Listener() { 
    @Override 
    public void call(Object... args) { 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 


      } 
     }); 
    } 
}; 
private Emitter.Listener onDisconnect = new Emitter.Listener() { 
    @Override 
    public void call(Object... args) { 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 


      } 
     }); 
    } 
}; 
+1

它的工作原理!謝謝!我猜套接字在活動中不起作用。 –