我在nodejs中有socket.io服务器,我可以从JavaScript客户端连接到它,但是从java / android我无法连接! 这是我的代码:
节点js:
var socket = require('socket.io')();
var users = {
desktop : {},
android : {}
}
socket.on('connection',function(client){
console.log(`new connection ! ${client.id}`);
client.on('intro',(user)=>{
user.client = client ;
user.cid = client.id ;
users[user.type] = user ;
console.log('users '+users);
})
});
socket.listen(2731)
console.log(`app running`);
这是java代码:
import io.socket.client.IO;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.AppCompatButton;
import android.view.View;
import android.widget.Toast;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
public class MainActivity extends AppCompatActivity {
io.socket.client.Socket socket ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
socket = IO.socket("http://192.168.1.103:2731");
JSONObject intro = new JSONObject();
intro.put("type","android");
intro.put("id",7);
socket.emit("intro");
} catch (URISyntaxException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
setContentView(R.layout.activity_main);
}
}
我使用localhost进行了测试:2731防火墙也关闭但是再次没有连接。 没有错误,也没有例外
答案 0 :(得分:1)
你的代码应该是这样的:
socket = IO.socket("http://192.168.1.103:2731");
socket.on(Socket.EVENT_CONNECT, new Emitter.Listener() {
@Override
public void call(Object... args) {
JSONObject intro = new JSONObject();
intro.put("type","android");
intro.put("id",7);
socket.emit("intro");
}
};
socket.connect();