问题
I am really struggling with opening a socket connection using sails.io and android. What I am trying to achieve at the moment is simply to print the socketid in the console of the sails.js server.
Android Side:
I am using nkzwa's socket.io.client library ( compile 'com.github.nkzawa:socket.io-client:0.4.2')
This is the code that I am using in android inside an AsyncTask:
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.0.80:3000/batches/");
} catch (URISyntaxException e) {}
}
@Override
protected Void doInBackground(Void... params) {
mSocket.connect();
mSocket.emit("getSocketID");
}
and my batchescontroller looks like this:
module.exports = {
getSocketID: function(req, res) {
if (!req.isSocket) return res.badRequest();
var socketId = sails.sockets.id(req.socket);
// => "BetX2G-2889Bg22xi-jy"
console.log(socketId)
return res.ok('My socket ID is: ' + socketId);
}
}
When running the task I thought that I would get the console log outputted in my sails instance.
Can anyone see what I am doing wrong?
回答1:
I got it working like this:
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.0.80:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
JSONObject obj1 = new JSONObject();
try {
obj1.put("url","/batches/getSocketID");
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("get",obj1);
mSocket.connect();
回答2:
Can you try first create a node client and try to connect the socket? I'm not sure if you're have certain that server side in sails are worker properly. am i right?
回答3:
To make a request use the url as the event
and to get a response use ack
in emit
method.
If you found the followig error Error (SAILS:HOOK:SOCKETS:PARSE_VIRTUAL_REQ):: Failed to parse incoming socket.io request
change http://192.168.11.111:1337
to http://192.168.11.111:1337?__sails_io_sdk_version=0.13.5
private Socket mSocket;
{
try {
mSocket = IO.socket("http://192.168.0.80:3000");
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("url", "/records");
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("get", jsonObject, new Ack() {
@Override
public void call(Object... args) {
Log.d(TAG, "records: " + args[0].toString());
}
});
来源:https://stackoverflow.com/questions/29650396/simple-sails-js-and-android-example