我是nodejs的新手,我想发布并获取数据到nodejs服务器,并在应用程序和服务器内实时。在这段代码中,我的代码不正确。我正在使用express
和socket
,我无法在应用程序中处理它。这两个都是正确的吗?
/**
* Module dependencies.
*/
var express = require('express');
var connect = require('connect');
var http = require('http').Server(app);
var io = require('socket.io');
var app = express();
var port = process.env.PORT || 8080;
// Configuration
app.use(connect.logger('dev'));
app.use(connect.json());
app.use(connect.urlencoded());
// Routes
require('./routes/routes.js')(app);
var server = io.listen(4732);
server.sockets.on('connection', function(socket) {
console.log('hello');
socket.on('user', function(data) {
if (data.type == "client") {
mk_socket = socket;
}
});
});
console.log('The App runs on port ' + port);
我的Android客户端:
SocketIO socketio = null;
try {
socketio = new SocketIO(SERVER_ADDRESS);
} catch (MalformedURLException e) {
e.printStackTrace();
}
socketio.connect(new IOCallback() {
@Override
public void onMessage(JSONObject json, IOAcknowledge ack) {
System.out.println("Server said: " + "SALAM");
//Toast.makeText(G.currentActivity, "SALAM", Toast.LENGTH_LONG).show();
}
@Override
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
@Override
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
//Toast.makeText(G.currentActivity, "an Error occured", Toast.LENGTH_LONG).show();
socketIOException.printStackTrace();
}
@Override
public void onDisconnect() {
System.out.println("Connection terminated.");
}
@Override
public void onConnect() {
System.out.println("Connection established");
//Toast.makeText(G.currentActivity, "Connection established", Toast.LENGTH_LONG).show();
}
@Override
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
//Toast.makeText(G.currentActivity, "Server triggered event", Toast.LENGTH_LONG).show();
}
});
socketio.emit("user", new JSONObject());
例如,当我使用时,我不会得到hello
:
socketio.emit("user", new JSONObject());
,谢谢