2016-09-14 94 views
2

我目前正在運行一個完全連接到我的JavaScript客戶端的Python SocketIO服務器。我使用socketio android example chat app來編寫Android代碼,它與NodeJS服務器完美協作,但是當我轉換到使用Python服務器時,它將無法連接。如何將Android應用程序連接到python-socketio後端?

如何從Android連接到Ptyhon-SocketIO服務器?

的Android代碼:

public class HomeActivity extends AppCompatActivity 
    implements NavigationView.OnNavigationItemSelectedListener { 

private final String TAG = "MainActivity"; 

Button btnCore0, btnCore1, btnCPUUsage; 
private ProgressBar progressBar; 

private Socket mSocket; 

{ 
    try { 
     mSocket = IO.socket(Constants.SERVER_URL); 
    } catch (URISyntaxException e) { 
     Log.e(TAG, e.getMessage()); 
    } 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_home); 
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
    setSupportActionBar(toolbar); 

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
    fab.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View view) { 
      Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
        .setAction("Action", null).show(); 
     } 
    }); 

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); 
    ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
      this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close); 
    drawer.setDrawerListener(toggle); 
    toggle.syncState(); 

    NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view); 
    navigationView.setNavigationItemSelectedListener(this); 

    btnCore0 = (Button) findViewById(R.id.btnCore0); 
    btnCore1 = (Button) findViewById(R.id.btnCore1); 
    btnCPUUsage = (Button) findViewById(R.id.btnCPUUsage); 
    progressBar = (ProgressBar) findViewById(R.id.progressBar); 

    // Make buttons invisible 
    btnCore0.setVisibility(View.INVISIBLE); 
    btnCore1.setVisibility(View.INVISIBLE); 
    btnCPUUsage.setVisibility(View.INVISIBLE); 
    // Make progress bar visible 
    progressBar.setVisibility(View.VISIBLE); 

    mSocket.on("status-update", onNewMessage); 
    mSocket.on(Socket.EVENT_DISCONNECT, onSocketDisconnected); 
    mSocket.connect(); 
} 

private Emitter.Listener onNewMessage = new Emitter.Listener() { 
    @Override 
    public void call(final Object... args) { 
     HomeActivity.this.runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       Log.d(TAG, "New message 090909***"); 
       JSONObject data = (JSONObject) args[0]; 
       int core0 = 0; 
       int core1 = 0; 
       int cpu_usage_in = 0; 
       try { 
        core0 = data.getInt("core0_in"); 
        core1 = data.getInt("core1_in"); 
        cpu_usage_in = data.getInt("cpu_usage_in"); 
       } catch (JSONException e) { 
        Log.e(TAG, e.getMessage()); 
       } 

       btnCore0.setText(getResources().getString(R.string.core0, String.valueOf(core0))); 
       btnCore1.setText(getResources().getString(R.string.core1, String.valueOf(core1))); 
       btnCPUUsage.setText(getResources().getString(R.string.cpu_usge, String.valueOf(cpu_usage_in))); 

       updateButtonBackgroundColor(btnCore0, core0); 
       updateButtonBackgroundColor(btnCore1, core1); 
       updateButtonBackgroundColor(btnCPUUsage, cpu_usage_in); 

       onServerDataReceived(); 
      } 
     }); 
    } 
}; 

接着是發射每秒的Pyhton服務器。這,我知道工作正常,因爲我可以從JavaScript應用程序連接到它。 Python代碼:

from flask import Flask, render_template 
from flask_socketio import SocketIO 
from gcm import GCM 

eventlet.monkey_patch() 
app = Flask(__name__) 
socket = SocketIO(app, logger=True, engineio_logger=True) 

class Server(threading.Thread): 
def __init__(self, thread_id): 
    threading.Thread.__init__(self) 
    self.threadID = thread_id 

def run(self): 
    print("Starting " + self.name) 
    serve() 
    print("Exiting " + self.name) 


def serve(): 
if __name__ == '__main__': 
    eventlet.wsgi.server(eventlet.wrap_ssl(eventlet.listen(('', 8000)), certfile='/home/garthtee/cert.pem', keyfile='/home/garthtee/privkey.pem'), app) 

server_thread = Server("Server-thread") 
server_thread.start() 
threads.append(server_thread) 
print("Started @ " + str(get_time())) 
while True: 
sensors.init() 
try: 
    for chip in sensors.iter_detected_chips(): 
     # print('%s at %s' % (chip, chip.adapter_name)) 
     for feature in chip: 
      if feature.label == 'Core 0': 
       core0 = feature.get_value() 
      elif feature.label == 'Core 1': 
       core1 = feature.get_value() 
    for x in range(1): 
     cpu_usage = str(psutil.cpu_percent(interval=1)) 
finally: 
    socket.emit('status-update', {'core0_in': core0, 'core1_in': core1, 'cpu_usage_in': cpu_usage, 'users': users}) 

    alert_checker(avg_temp, users) 
    sensors.cleanup() 
    time.sleep(1) 

以下錯誤顯示出來:

SSLError:[SSL:SSL_HANDSHAKE_FAILURE] SSL握手失敗(_ssl.c:1754)

+0

完成,如果有人可以幫助,我會很感激。 – Garth

+0

你需要用確切的術語解釋你的意思是「它不會連接」。服務器是否完全忽略了Android應用,例如,如果服務器URL錯誤會發生什麼? – Miguel

+0

服務器發出消息確定,但Android應用程序不會收到消息。我有上面的Android代碼,自從我運行一個NodeJS服務器以來,我沒有改變它,因此連接工作。 – Garth

回答

1

我下載的SocketIO python庫Github

我修改了這樣的示例代碼:

import socketio 
import eventlet 
import eventlet.wsgi 
from flask import Flask, render_template 

sio = socketio.Server() 
app = Flask(__name__) 

@app.route('/') 
def index(): 
    """Serve the client-side application.""" 
    return render_template('index.html') 

@sio.on('connect', namespace='/') 
def connect(sid, environ): 
    print("connect ", sid) 

@sio.on('add user', namespace='/') 
def login(sid, environ): 
    print("login ", sid) 
    sio.emit('login', room=sid) 

@sio.on('new message', namespace='/') 
def message(sid, data): 
    print("message ", data) 
    sio.emit('reply', room=sid) 

@sio.on('disconnect', namespace='/') 
def disconnect(sid): 
    print('disconnect ', sid) 

if __name__ == '__main__': 
    # wrap Flask application with engineio's middleware 
    app = socketio.Middleware(sio, app) 

    # deploy as an eventlet WSGI server 
    eventlet.wsgi.server(eventlet.listen(('', 8000)), app) 

然後我克隆Android example chat項目,我在Constants.java改變的唯一事情:

public static final String CHAT_SERVER_URL = "http://MY_LOCAL_IP:8000"; 

和Android應用程序可以連接。 我在應用程序中看到它,也在python控制檯中看到它。 如果你刪除了一些不必要的解析部分(應用程序崩潰,因爲響應不同),你也可以在python中看到你的消息。

您是否嘗試過首先不使用SSL來運行您的服務器應用程序?

也許這就是問題所在。 在Android上,您可以使用IO.setDefaultSSLContext(SSLContext sslContext)來設置SSL。

+0

我嘗試過使用此socket.io-client-java,但無法連接到它。當我使用NodeJS後端時,它可以很好地工作,但不適用於Python。也許有什麼需要改變的Python後端? – Garth

+0

您是否使用相同的SocketIO版本? – danesz

+0

謝謝,我修改了答案。 @Garth你可以在沒有SSL的情況下試用嗎? – danesz

相關問題