Good morning why this code don't work (server respond but "io.on" no):
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
//this code not work in console // even it can not see
io.on('connection', function(socket) {
console.log('a user connect');
socket.on('disconnect', function() {
console.log('a user disconnect');
});
});
//server respond
http.listen(3000, function() {
console.log('Server running at 3000');
});
I'm a beginner, express and socket.io i downloaded by npm
You need to have a server as well as a client which will make a connection to the socket io server.
Based on what I understood from your code, I guess you want to do something like this:
First your server.js:
#!/usr/bin/env node
var http = require('http');
var express = require('express');
var app = express();
var io = require('socket.io');
var port = 3000;
app.set('port', port);
var server = http.createServer(app);
server.listen(port);
var socketio = io.listen(server);
setInterval(function() {
console.log("Emitting..");
socketio.emit('data', {"x":"123"});
}, 2000);
module.exports = app;
Then your client.html: (I am writing a client, which will log into browser console.)
<html>
<head></head>
<body>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
var socket = io.connect("http://localhost:3000/");
socket.on('connect', function() {
console.log('connected');
});
socket.on('disconnect', function(){
console.log('disconnected');
});
socket.on("data", function(data) {
console.log(data);
});
</script>
</body>
That's it. Now start your server with node server.js and then, open up client.html in your browser and check console. Let me know, if there's anything unclear.
Related
I am trying to connection to socket server on port 8080 but keep getting this error Connection to IPAddress:8080 timed out!
this my server code
const express = require("express");
var http = require('http').createServer(app);
var io = require('socket.io');
const socket = io(http);
http.listen(8080, () => {
console.log(`Server is running on port ${PORT}.`);
});
how to solve it please ?
You have to write more code of socket you can not connect to socket direct
You have to write connection function
Follow This tutorial to know basics of socket
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
var port = 8080; // set our port
app.get('/', function(req, res) {
res.sendfile('index.html');
});
io.on("connection", function (socket) {
// Everytime a client logs in, display a connected message
console.log("Server-Client Connected!");
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(port, () => {
console.log('Magic happens on port ' + port); // shoutout to the user
});
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
</script>
<body>Hello world</body>
</html>
after running server check localhost:8080
my folder structure for socket.io is as following:
node_modules/socket.io/
my folder structure for socket.io.js is as following:
/node_modules/socket.io-client/dist/socket.io.js
var express = require('express');
var http= require('http').Server(express);
var io= require('socket.io') (http);
var app = express();
io.on('connection', function(socket){
socket.on('chat', function(msg){
io.emit('chat',msg);
});
});
io.on('disconnect', function() {
console.log('user is disconnected');
});
And view is as follows:
<script src="/node_modules/socket.io-client/dist/socket.io.js"></script>
<script src="/js/jquery-2.1.4.min.js"></script>
<script>
$(function(){
var socket= io();
$('form').submit(function(e){
e.preventDefault();
socket.emit('chat', $('#input').val());
$('#input').val('');
return false;
});
socket.on('chat', function(msg){
$('#sent').append(msg);
});
});
</script>
and errors are:
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not defined
Without creating server you are creating socket instance ,you can pass app to your socket.js or you can export socket to other module and use accordingly....It should be like this
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
First off, a node.js server does not server ANY files by default. For a file to be served by the server, there must be a route handler that has code to send that particular file. So, that explains why this doesn't work:
<script src="/node_modules/socket.io-client/dist/socket.io.js"></script>
because there is no route handler in your server for the path "/node_modules/socket.io-client/dist/socket.io.js".
But, socket.io solves this problem for you. The socket.io server automatically installs a route for:
/socket.io/socket.io.js
And it will reach into that node_modules/socket.io/client directory and send the socket.io.js file when it sees the above request.
So, change your script tag to this:
<script src="/socket.io/socket.io.js"></script>
And, the socket.io server will automatically send the socket.io.js file from the dist directory.
It looks like your server initialization is also not correct because you don't pass express to your http server, you pass app. Change this:
var express = require('express');
var http= require('http').Server(express);
var io= require('socket.io') (http);
var app = express();
io.on('connection', function(socket){
socket.on('chat', function(msg){
io.emit('chat',msg);
});
});
io.on('disconnect', function() {
console.log('user is disconnected');
});
to this:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(80);
io.on('connection', function(socket){
socket.on('chat', function(msg){
io.emit('chat',msg);
});
});
io.on('disconnect', function() {
console.log('user is disconnected');
});
or, a bit simpler version:
var express = require('express');
var app = express();
var server = app.listen(80);
var io = require('socket.io')(server);
io.on('connection', function(socket){
socket.on('chat', function(msg){
io.emit('chat',msg);
});
});
io.on('disconnect', function() {
console.log('user is disconnected');
});
I was working on a node js application with socket.io. I looked at some of the answers on SO but they could not help me with my problem. The error I am getting is
Failed to load resource: the server responded with a status of 404 (Not Found)
localhost/:10 Uncaught ReferenceError: io is not defined
Here is my directory structure:
Judgement
|----node_modules
|----|----express
|----|----socket.io
|----public
|----|----css
|----|----|----judgementMain.css
|----|----js
|----|----|----form.js
|----|----index.html
|----server.js
|----package.json
In my index.html page
I have the following link to socket.io.js
<script type="text/javascript" src="socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io();
</script>
<script type="text/javascript" src="js/form.js"></script>
The contents of server.js are as follows
var express = require('express');
var app = express();
var path = require('path');
// Define the port to run on
app.set('port', 3000);
app.use(express.static(path.join(__dirname, 'public')));
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function (socket) {
console.log('A user connected');
socket.on('disconnect', function() {
console.log('A user disconnected');
});
});
Can someone explain what I am doing wrong? I only just started with node js and express and socket.io, so any help is appreciated.
Thanks
I see a couple issues:
First, in your HTML, it should be src="/socket.io/socket.io.js" with the leading slash.
Second, you are creating two http servers but only actually starting one of them, when you should be using just one. Your socket.io stuff doesn't work because you're giving it an http server that you never started.
Change to this where you are giving socket.io the http server that express is using and that has been started on your desired port:
var express = require('express');
var app = express();
var path = require('path');
// Define the port to run on
app.set('port', 3000);
app.use(express.static(path.join(__dirname, 'public')));
// Listen for requests
var server = app.listen(app.get('port'), function() {
var port = server.address().port;
console.log('Magic happens on port ' + port);
});
var io = require('socket.io')(server);
io.on('connection', function (socket) {
console.log('A user connected');
socket.on('disconnect', function() {
console.log('A user disconnected');
});
});
i have socket io redis and express pubsub going on, in my local host it works just fine i am using laravel events to publish to redis then socket io is supposed to emit the message, its working okay on local host but on my production server which is an ec2 vm it only gets to connect and i can see a console message 'connected' but it does not emit any events even though messages are being published to redis here is my client and server
//client
<script type="text/javascript">// <![CDATA[
var socket = io.connect('http://127.0.0.1:3000/');
socket.on('connect', function(data){
//socket.emit('subscribe', {channel:'score.update'});
console.log('connected');
});
socket.on('notification.update', function (data) {
//Do something with data
console.log('Notification Caught: ', data);
});
// ]]></script>
//server
var express = require('express'),
http = require('http'),
server = http.createServer(app);
var app = express();
const redis = require('redis');
const io = require('socket.io');
const client = redis.createClient();
server.listen(3000, 'localhost');
io.listen(server).on('connection', function(client) {
const redisClient = redis.createClient()
redisClient.subscribe('notification.update');
});
redisClient.on("message", function(channel, message) {
//Channel is e.g 'score.update'
client.emit(channel, message);
});
client.on('disconnect', function() {
redisClient.quit();
});
});
You need to change the listening of your server:
Change these:
var express = require('express'),
http = require('http'),
server = http.createServer(app);
var app = express();
const redis = require('redis');
const io = require('socket.io');
const client = redis.createClient();
And
server.listen(3000, 'localhost');
io.listen(server).on('connection', function(client){
//Code
});
To:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
And
io.on('connection, function(client){
//Code
});
server.listen(3000, function(){
console.log("Listening on :3000");
});
I am trying to sent a basic message when users connect and disconnect. Later i want to sent parameters back and forth. But with the following code i do not get the messages print out on the server when they connect/disconnect.
When i replace io.on with server.on i can get the message 'User connected' but not user disconnected when i refresh/close the page. This however is buggy, since not everytime i refresh it logs the message and on first time it sometimes log the message multiple times.
server.js
var //io = require('socket.io'),
http = require('http'),
express = require('express');
var PORT = process.env.PORT || 8080,
HOST = process.env.HOST || 'localhost';
var app = express();
app.use(express.static(__dirname + '/views'));
app.get('/', function (req, res) {
res.sendfile(__dirname + 'index.html');
});
server = http.Server(app);
//io = io.listen(server);
var io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('User connected');
io.on('disconnect', function(socket) {
console.log('User Disconnected');
});
});
server.listen(PORT, HOST, null, function() {
console.log('Server listening on port %d in %s mode', this.address().port, app.settings.env);
});
New code:
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
var PORT = process.env.PORT || 8080,
HOST = process.env.HOST || 'localhost';
server.listen(PORT);
app.use(express.static(__dirname + '/views')); //need this for my directory structure.
app.get('/', function (req, res) {
res.sendfile(__dirname + 'index.html');
}); //Need this to call my page.
io.on('connection', function( client ){
console.log('Connected');//this does not work.
io.on('disconnect', function( client) {
console.log(client);
});
});
Try reconfiguring your socket, and server instantiation:
var express = require('express'),
app = express(),
server = require('http').createServer(app),
io = require('socket.io').listen(server);
server.listen(process.env.PORT || 3000);
io.on('connection', function( client ) {
console.log(client) //this will now work
client.on('disconnect', function( id ) {
console.log('user with ID ' + id + ' has disconnected');
});
});
First of all you need to be sure if you have included the client side socket.io files.
<script src="/socket.io/socket.io.js"></script>
Then you need to initialize the socket connection.
<script>
var socket = io();
</script>
The above changes will be in your index.html file.
Now in server.js file,
io.sockets.on('connection', function(socket) {
console.log("User connected");
socket.on('disconnect', function() {
console.log('Got disconnect!');
});
});