我正在尝试为我的大学制作聊天应用程序但我的应用程序无法与我在heroku应用程序上托管的NodeJS服务器进行通信。
1)应用程序的第一个活动将从用户输入用户名并将其发送到服务器,我将其保存为会话的变量。
2)之后聊天活动将会打开。
这是用户名输入活动的代码:
public class MainActivity extends AppCompatActivity {
private Button button;
private EditText edit;
public String username;
private Socket mSocket;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.buttonSubmit);
edit = (EditText) findViewById(R.id.nickedit);
username = edit.getText().toString();
{
try {
mSocket = IO.socket("https://backendchatio.herokuapp.com/");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
check();
send();
}
});
}
public Boolean check() {
if (edit.getText().toString().trim().isEmpty()) {
return false;
} else {
return true;
}
}
public void send() {
if (check() != true) {
Toast.makeText(this, "Error", Toast.LENGTH_SHORT);
}
else {
mSocket.emit("username",username);
Intent intent = new Intent(MainActivity.this, Chatting.class);
intent.putExtra("username", username);
startActivity(intent);
}
}
这是NodeJS服务器的代码:
var express = require('express');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var listen = process.env.PORT || 3000;
app.use(express.static(__dirname + '/public'));
app.get('/', function(req,res) {
console.log("Index");
});
io.on('connection', function(socket) {
console.log("A user has connected");
socket.on('disconnect', function() {
console.log("A user has disconnected");
});
socket.on('username', function(username) {
socket.username = username;
console.log("A new user named" +username+ "Has joined");
});
socket.on('message',function(data) {
socket.broadcast.emit('message', function(username) {
username: socket.username;
message: data;
});
})
});
http.listen(listen, function() {
console.log("Server runnin at "+listen);
})
问题是,每当我提交用户名时,我都希望它能够登录我的控制台(Heroku日志),但它没有
我是Android开发和Websockets的新手
提前致谢
答案 0 :(得分:0)
诊断问题的一些问题:
1)heroku logs --tail
是否记录Server runnin at ...
?
2)启动应用时,heroku logs --tail
是否会A user has connected
?
3)您的应用是否正确启动/正确启动Chatting.class?
4)Android Monitor(Alt + 6)是否会输出任何错误?