I spend a few days on the problem.I am trying to build a page with socket.io.
I am a beginer of node.js & socket.io. I read the socket.io doc, and build the page step by step.
And then i got a error, Uncaught ReferenceError: io is not defined
But i can get the js content from http://localhost:3000/socket.io/socket.io.js
I use var socket = io.connect('http://localhost') or use var socket = io() on client side. Neither is ok.What show i do?
Here is my code in server side:
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 3000;
http.listen(port, function(){
console.log('Server listening at port %d', port);
})
In client side:
var socket = io();
socket.on('news', function(data){
console.log(data);
})
On the client side, you should use the server.io client
import io from 'socket.io-client';
You can run
npm i socket.io-client
to install the dependency or alternatively you can serve the file socket.io.js found in the dist folder provided from https://www.npmjs.com/package/socket.io-client
<script src="/socket.io/socket.io.js"></script>
Not tested
In your pug template, you can do in head or body,
doctype html
html(lang="en")
head
script(src="/socket.io/socket.io.js").
//Your logic here
Related
While working with localhost I used the following code to implement socket functionality-
Server Side
var express = require('express');
var app = express();
const io = require('socket.io')(5000);
Client Side
<script src="http://localhost:5000/socket.io/socket.io.js"></script>
<script>const socket = io.connect('http://localhost:5000');</script>
The above code worked fine for me locally. Earlier tried use the code given in the official documentation, but it did not work. I got a 404 error when trying to load socket.io.js file and it said 'io is not defined' on the client side. That code is given below-
Server Side
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
Client Side
<script src="/socket.io/socket.io.js"></script>
<script>var socket = io.connect('http://localhost');</script>
Now I need to deploy the app to Heroku and don't know how to do the socket functionality. I tried both the above ways but none worked in Heroku. I am getting '404 error' and 'io is not defined'. The server-side code is written in ./app.js and client-side code written in ./public/index.html.
How do I get this socket functionality to work in Heroku and also why is the official code not even working locally?
Trying to get the same thing working, don't have all the answers but on heroku you need to grab the port from the environment variable.
// Needed for Heroku serving
if (process.env.PORT > 0)
port = process.env.PORT;
else
port = 5000;
// create the express server (app) and the socket io server (io)
const app = express();
const server = app.listen(port, () => {
console.log("Listening on port: " + port);
});
const io = require('socket.io')(server);
Client Side
const socket = socketIOClient('APPNAME.herokuapp.com:80');
socket.emit("MsgType", "Payload")
My structure
game.js
node_modules\
public\
|index.html
|js\main.js
game.js is nodejs server and in plubic folder is client side
In index.html I have
<script src="/socket.io/socket.io.js"></script>
But when i run in web browser it say
GET http://localhost:1000/socket.io/socket.io.js 404
(index):3 Uncaught ReferenceError: io is not defined
at (index):3
But when i download socket.io.js and make like this
game.js
node_modules\
public\
|index.html
|js\main.js
|socket.io\socket.io.js
And run again it localhost:1000 say
localhost:1000/socket.io/?EIO=3&transport=polling&t=Lg5U91n 404 (Not Found)
what is mistake. I run in window. How to fix that thank.
You will need to include socketio-client on the client side via the script tag. That will allow IO to be defined.
<script>
var socket = io.connect('http://localhost:1000');
socket.on('connect', function(data) {
//Do Something here
});
</script>
You will also need to make sure on your backed (the server that socketio is connecting to) has socketio properly defined and is being used in the HTTP server. An example would be:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(1000);
io.on('connection', function(client) {
console.log('Client connected...');
//socket code here
});
Its very hard for us to help you without any code sample of what you are working with. The example provided is a very BASIC way of getting socketio up and running.
Checkout the socketio client github that has a quick and simple demonstration of what to do as well:
Socket.io Client Github
This function doesn't work in my app. I can't receive a message (socket.emit) from the server to the client (socket.on).
But i don't have this problem in the inverse (client to server).
I use cloud9 and the chat example from them works fine.
Here is my code for the server :
var http = require('http');
var path = require('path');
var async = require('async');
var socketio = require('socket.io');
var express = require('express');
var router = express();
var server = http.createServer(router);
var io = socketio.listen(server);
router.use(express.static(path.resolve(__dirname, 'client2')));
io.on('connection', function (socket) {
socket.emit('hello', 'i changed'); // !!!
});
server.listen(process.env.PORT || 3000, process.env.IP || "0.0.0.0", function(){
var addr = server.address();
console.log("Chat server listening at", addr.address + ":" + addr.port);
});
and the code for the html page :
<html>
<head>
<title>test</title>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
socket.on('hello', function (msg) { // !!!
document.innerHTML = msg;
});
</script>
</head>
<body>
<p>normal page</p>
</body>
</html>
And there is no change...
edit : with console.log either.
But the message seems sent with the socket :
Debugger listening on port 15454
info - socket.io started
Chat server listening at 0.0.0.0:8080
debug - served static content /socket.io.js
debug - client authorized
info - handshake authorized 13XpSYGuXzMpMeyFsRfO
debug - setting request GET /socket.io/1/websocket/13XpSYGuXzMpMeyFsRfO
debug - set heartbeat interval for client 13XpSYGuXzMpMeyFsRfO
debug - client authorized for
debug - websocket writing 1::
debug - websocket writing 5:::{"name":"hello","args":["i changed"]}
Can you help me please ?
You need to change
var socket = io.connect();
by
var socket = io.connect('http://0.0.0.0:8080');
var socket = io.connect() <- this should specify the domain to which you are connecting.
So i did alot in this, trying to get it to work, it sorta did but i don't work like you do, i'm a beginner and not compatible with how you code but i've figured out that the problem is the port the io is using
var io = socketio.listen(server);
or where the html is getting the connection
<script src="/socket.io/socket.io.js"></script>
to me, the html is requesting a js file in it's own dir, but it shouldn't.
When i use socket.io, i put this in the server
var client = require("socket.io").listen(8080).sockets
The main part is the listen, it listens on the port 8080 and in my html i do
var socket = io.connect("http://127.0.0.1:8080");
Which works, i'm sorry for this, i am mostly sure this isn't an answer but i've tried, i hope you get it done, even if a year and 3 months have passed.
$(function(){
var socket = io();
socket.on('hello',function(data){
$('#lblmsg').text(data.message);
});
});
this is something I am working with. in the 4th line of my code, data is passed and data.message is retrieved. but you directly equated msg with the innerhtml, on the html page(in the block you commented \!!!)
see if you are still working on it!
I am attempting to recreate this tutorial using typescript, routing, and jade. My code compiles and runs as expected, the jade file is served correctly, but there doesn't seem to be a connection between the client side socket and server side socket. For reference, the code from the tutorial is set like this:
Javascript file:
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
});
html file:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
And mine looks like this:
Server side:
import io = require('socket.io');
var server: SocketIO.Server = io();
server.on('connection', function(socket){
console.log('A user connected');
});
Client side:
declare var io: SocketIOClientStatic;
var socket = io();
I've moved the relevant server and client side code to different locations and tried a few different things. I've used regular javascript (exactly like the tutorial) for the client side, I've moved the script into the jade file, and I've moved the server side script around app.ts and index.ts (which app.ts routes to). I haven't been able to get the logged message from a connection event.
Your Javascript (a little bit rewritten):
var io = require('socket.io');
var server = io(http);
server.on(...);
Your Typescript:
import io = require('socket.io');
var server: SocketIO.Server = io();
^^ where is `http`?
server.on(...)
EDIT: The answer appears to be no.
I'm new to Node.js, bower and Socket.IO and I'm not sure what I need for my purpose.
I'm making an app that has a frontend (where browsers connect) and a backend (a single Node.js server).
What do I need to create a Socket.IO server instance on the backend? What do I need on the client-side? Does the Socket.IO package contain both?
First install socket.io using below command
npm install socket.io
and the call socket.io in your server js File
var io = require('socket.io');
And the create connection in your server js file
var app = express();
app.get('/', function(req, res){
fs.readFile('index.html', function(Error,data){
res.writeHead(200,{'Content-Type':'text/html'});
res.write(data);
res.end();
});
});
server = http.createServer(app);
var IO = io.listen(server);
server.listen(3000);
IO.sockets.on('connection', function(socket) {
socket.on('msg_to_server', function(data) {
console.log(data);
});
});
Add this script inside head Tag in your index.html
<script src="/socket.io/socket.io.js"></script>
in your index.html create socketio connection
var socketio = io.connect("127.0.0.1:3000");
send some data to server following way
socketio.emit('msg_to_server',{ message : 'some data' });