I am learning nodejs event driven programming using socket.io
, so that I could build a chat app.
So, I created a Server
and Client
running at different ports, in localhost
right now.
Server at 8080
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http, {origins: '*.*', transports: ['websocket', 'xhr-polling']});
var port = process.env.PORT || 8080;
http.listen(port, function () {
console.log('Cat Server listening at http://127.0.0.1:%d', port);
});
app.use(express.static(__dirname + '/public'));
io.on('connection', function (socket) {
console.log('Connection to client established ', socket);
var addedUser = false;
// when the client emits 'love event', this listens and executes
socket.on('LoveEvent', function (data) {
console.log("we tell the client to execute 'logevent'")
socket.broadcast.emit('LoveEvent', {
username: socket.username,
message: data
});
});
);
Client at 3000
Client is connecting to server 8080 via socket.io
I have following code in public/chat.js
which is included in public/index.html
var socket = io();
socket.connect('http://localhost:8080', {transports: ['websocket', 'xhr-polling']})
console.log("Connection to Cat socket server, ", socket)
And, public/index.html
is
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script src="/chat.js"></script>
The client structure is
$ ll
total 24
-rw-r--r-- 1 prayagupd staff 30 Nov 1 20:18 README.md
-rw-r--r-- 1 prayagupd staff 325 Nov 1 20:18 Server.js
drwxr-xr-x 91 prayagupd staff 3094 Oct 26 18:11 node_modules
-rw-r--r-- 1 prayagupd staff 249 Nov 1 20:18 package.json
drwxr-xr-x 8 prayagupd staff 272 Nov 1 20:22 public
with node_modules
having socket.js
$ ll node_modules/socket.io/lib/
total 80
-rw-r--r-- 1 prayagupd staff 5411 Oct 26 15:59 client.js
-rw-r--r-- 1 prayagupd staff 8933 Oct 26 15:59 index.js
-rw-r--r-- 1 prayagupd staff 5366 Oct 26 15:59 namespace.js
-rw-r--r-- 1 prayagupd staff 9493 Oct 26 15:59 socket.js
BUT
When I start my server
$ node Server.js
Cat Server listening at http://127.0.0.1:8080
and Client,
$ node Client.js
Cat client running at localhost:3000
I expect a connection message at server-side, as I'm debugging with message in Server.js
as console.log('Connection to client established ', socket);
I manually tried creating socket
from chorme console and sent an event, the server does not seem to subscribe it.
s.connect("http://localhost:8080", {autoConnect : true})
Socket {io: Manager, nsp: "/", json: Socket, ids: 0, acks: Object…}
s.emit("LoveEvent", "Love")
Socket {io: Manager, nsp: "/", json: Socket, ids: 0, acks: Object…}
Also, when the client at browser, has following 404 error
on transport=polling
in browser console,
I don't know why is it polling on port 3000, which is itself.
It was working well, when everything was in the same server. I refactored it and now :(
I have both backend and frontend code here => prayagupd/lovejs