I don't know what I'm missing. No error is thrown or anything, it just doesn't connect.
Server side code
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Run when client connects
io.sockets.on('connection', socket => {
console.log('New Conncection...')
})
const PORT = 4000 || process.env.PORT;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
Client Side Code
var io = require('socket.io-client')
var socket = io.connect('http://localhost:4000', {reconnect: true});
Here is a simple working example:
File structure:
.
├── public
│ └── index.html
└── server.js
server.js:
const path = require('path');
const http = require('http');
const express = require('express');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
// Set static folder
app.use(express.static(path.join(__dirname, 'public')));
// Run when client connects
io.sockets.on('connection', (socket) => {
console.log('New Conncection...');
io.sockets.emit('event', 'everyone');
socket.on('disconnect', () => {
console.log('disconnected');
});
});
const PORT = 4000 || process.env.PORT;
server.listen(PORT, () => console.log(`Server running on port ${PORT}`));
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/socket.io-client#2/dist/socket.io.js"></script>
<script>
document.addEventListener('DOMContentLoaded', () => {
var socket = io('http://localhost:4000', { reconnection: true });
socket.on('connect', function() {
console.log('socket connection success');
});
socket.on('event', function(data) {
console.log('data:', data);
});
socket.on('disconnect', function() {
console.log('socket disconnect');
});
});
</script>
</body>
</html>
The logs for server-side:
Server running on port 4000
New Conncection...
disconnected
New Conncection...
The logs for client-side:
socket connection success
data: everyone
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
I want to use soket.io in my app and use module.export for mvc express app.
May server code is:
var express = require('express')
, app = express()
, router = express.Router();
var http= require('http').Server(app);
var io=require('socket.io')(http);
app.io = require('socket.io')();
...
//api
app.use(require('./controllers'));
app.listen(config.port, function() {
console.log('Listening on port ' + config.port)})
And my controllers/ index :
var express = require('express')
, router = express.Router();
..
router.get('/', function(req, res) {
res.send('hi')
});
router.use('/chat', require('./chat'));
module.exports = router
</code>
My chat.js file is:
var app = require('express')
, chat = app.Router();
var http= require('http').Server(app);
var io = require('socket.io')(http);
var path = require("path");
chat
.get('/', function(req, res) {
let reqPath = path.join(__dirname, '../');
// res;
io.on('connection', function(socket){
console.log('a user connected');
})
res.sendFile(reqPath +'/views/index.html'); })
io.on('connection', function(socket){
console.log('a user connected');
});
The code send my html file and show my result. But don't show console.log('a user connected'); in my console.
<code><!DOCTYPE html>
<html>
<head>
<title>Hello world</title>
</head>
<script src = "/socket.io/socket.io.js"></script>
<script>
var socket = io();
function sendMessage() {
var msg = document.getElementById('message').value;
if(msg) {
socket.emit('msg',msg);
}
}
socket.on('msg', function(data) {
document.getElementById('message-container').innerHTML += '<div>' + data.ChatMessage + '</div>'
})
</script>
<body>
<div id = "error-container"></div>
<input type = "text" id = "message">
<button type = "button" name = "button" onclick = "sendMessage()">Send</button>
<div id = "message-container"></div>
</body>
</html></code>
here is my code app.js
var express = require('express');
var app = express();
var http = require('http').Server(app);
app.use(express.static('Public'));
app.get("/send", function (request, response) {
response.sendFile('index.html', {root : './views'});
});
var listener = http.listen(process.env.HOSTNAME ||
'myhostname.com/nodejs/restapi' ,function(){
console.log('server running');
});
and my views/index.html
<script src="../client.js" type="text/javascript"> </script>
and my Public/client.js
$(function() {
$.get('/Nodejs/Restapi/send', function(send) {
console.log('hello world :o');
});
});
i dont know whats wrong its working perfectly in localhost
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');
});
});
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.