我试图创建一个聊天应用程序,所以我创建了一个简单的原型。后端服务器使用flask-socketio框架。我使用了这份文档https://flask-socketio.readthedocs.io/en/latest/,下面是烧瓶后端的代码:
from flask import Flask
from flask_socketio import SocketIO, send
app = Flask(__name__)
app.config['SECRET_KEY'] = 'mysecret'
socketio = SocketIO(app, cors_allowed_origins="*")
@app.route('/main')
def test():
return 'Test'
@socketio.on('message', namespace = '/nice')
def handleMessage(msg):
print('Message: ' + msg)
send(msg, broadcast = True)
if __name__ == '__main__':
socketio.run(app, host = '0.0.0.0', port = 5000, debug = True)
要将后端与android连接,我使用了Java socketIO文档:https://github.com/socketio/socket.io-client-java由于某种原因,当我使用emuator时一切正常,但是当我使用手机时,什么也没发生。这是Android Studio 主要活动(唯一的活动)
public class MainActivity extends AppCompatActivity {
private Button button;
private TextView text;
private EditText edit;
private String message;
private String link = "http://192.168.0.106:5000/nice";
private io.socket.client.Socket mSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = findViewById(R.id.button);
text = findViewById(R.id.text);
edit = findViewById(R.id.edit);
Server server = new Server(link);
new Thread(server).start();
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String message = edit.getText().toString().trim();
if (!message.isEmpty()) {
mSocket.emit("message", message);
}
}
});
}
private class Server implements Runnable{
private String uri;
public Server(String uri){
this.uri = uri;
}
@Override
public void run() {
try {
mSocket = IO.socket(uri);
mSocket.connect();
mSocket.open();
Log.d("myTag", "Pavyko");
} catch (URISyntaxException e) {
Log.d("myTag", e.getMessage());
}
mSocket.on("message", new Emitter.Listener() {
@Override
public void call(Object... args) {
message = args[0].toString();
runOnUiThread(new Runnable() {
@Override
public void run() {
text.setText(message);
}
});
}
});
}
}
}
清单有:
<uses-permission android:name="android.permission.INTERNET"/>
和成绩:
implementation ('io.socket:socket.io-client:1.0.0') {
// excluding org.json which is provided by Android
exclude group: 'org.json', module: 'json'
}
没有错误,所以我真的不知道该怎么办...