I have a Node.js server using socket.io and an android app. I want my app to connect to the server. (I work locally)
So first I start the server : command prompt
Here is the code of it :
var express = require('express'); // call express
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 1234;
app.get('/',function(req,res){
res.send("Welcome to my socket");
});
io.on('connection', function (socket) {
console.log('one user connected : '+socket.id);
// when the client emits 'new message', this listens and executes
socket.on('new message', function (data) {
// we tell the client to execute 'new message'
console.log('this is message :',data);
});
});
http.listen(port, function () {
console.log('Server listening at port %d', port);
});
And then I try to connect from my activity here :
public class AvisActivity extends AppCompatActivity {
private Socket mSocket;
{
try {
mSocket = IO.socket("http://172.21.191.234:1234");
} catch (URISyntaxException e) { Log.v("AvisActivity", "error connecting to socket");}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_avis);
Log.v("AvisActivity", "try to connect");
mSocket.connect();
Log.v("AvisActivity", "connection sucessful");
}
}
My problem is that I never see the log "one user connected" on the server but I always see the "try to connect" and " connection sucessful" on the android log.
Can someone solve this mystery for my please ?
UPDATE
My code worked fine, but I encounter some Wifi configuration that blocks web socket (and actually my school did, that's where my problems came from)
UPDATE
My code worked fine, but I encounter some Wifi configuration that blocks web socket (and actually my school did, that's where my problems came from). But I don't really know how they blocked it.
Also, later in my project when I deploy to an OVH server, I got problems by using the 1234 port. Make sure to use a port available/unlocked by your provider.