【发布时间】:2015-11-10 00:17:31
【问题描述】:
我正在尝试在 node.js 和 android 之间创建一个基本的聊天应用程序,当我同时运行服务器和客户端时,我可以在日志中看到它们连接并且我的 android 应用程序发送了一条消息,但服务器从未收到它,我的安卓代码是:
private Socket socket;
{
IO.Options opts = new IO.Options();
opts.forceNew = true;
opts.reconnection = true;
try {
socket = IO.socket("http://192.168.3.7:100");
} catch (URISyntaxException e) {
Log.e("abc", "index=" + e);
}
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_promociones);
socket.on("new message", onNewMessage);
socket.connect();
}
class WifiScanReceiver extends BroadcastReceiver {
@SuppressLint("UseValueOf")
public void onReceive(Context c, Intent intent) {
ObjWifi.startScan();
messages =String.valueOf(id)+';'+ Arrays.toString(ret)+';'+String.valueOf(zona);
socket.emit(messages);
String str;
int i1 = r.nextInt(4 - 1) + 1;
if (zona == 0) {
str = "img_" + 4;
} else {
str = "img_" + zona + "_" + i1;
}
fondo.setImageDrawable(getResources().getDrawable(getResourceID(str, "drawable", getApplicationContext())));
}
}
我还想让传入的消息(总是数字)存储在名为 zona 的变量中。
我的服务器端代码是:
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var messages = [{
text: "Hola soy un mensaje",
author: "Daniel"
}];
app.use(express.static('public'));
io.on('connection', function(socket) {
var currentdate = new Date();
var datetime = currentdate.getDate() + "/"
+ (currentdate.getMonth()+1) + "/"
+ currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":"
+ currentdate.getSeconds();
console.log('Alguien se ha conectado con Sockets',datetime);
socket.emit('messages', messages);
socket.on('disconnect',function(){
console.log('Alguien se ha desconectado',datetime);
});
socket.on('new-message', function(data) {
messages.push(data);
io.sockets.emit('messages', messages);
});
});
server.listen(100, function() {
console.log("Servidor corriendo en http://localhost:100");
});
【问题讨论】:
-
在你的代码中缩进,因为它很难阅读