I am studying node and express. I have a table of inventory item and I want to view this on my web browser that's why I used socket.io with express.
But when there's a connection I can't load the data. Here's my code:
server.js
var express = require('express');
var app = express();
var mysql = require('mysql');
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 8000;
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'node'
});
app.use(express.static(__dirname + '/public'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));
app.get('/', function(req, res) {
res.sendFile(__dirname + '/index.html');
});
connection.connect();
/**example from express
connection.connect();
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
console.log(rows);
});
connection.end();
**/
function loadList() {
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
return rows;
});
}
io.on('connection', function(socket){
console.log('A user is connected!!');
socket.on('inventory list', function(data){
return 'hello world'; // i pass a simple return to test if this can return something
/*
connection.query('SELECT * FROM inventory', function(err, rows, fields){
if(err) throw err;
console.log(rows);
});
*/
});
socket.on('disconnect', function() {
console.log('user disconnected!');
});
});
http.listen(8000, function() {
console.log('Listening on ' + port);
});
index.html
<!DOCTYPE>
<html>
<head>
<title>Invertory Sample</title>
<link rel="stylesheet" type="text/css" href="/bower_components/bootstrap/dist/css/bootstrap.min.css" />
<link rel="stylesheet" type="text/css" href="/bower_components/font-awesome/css/font-awesome.min.css" />
</head>
<body>
<p>sample</p>
<p class="test"></p>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
try {
var socket = io.connect('http://127.0.0.1:8000');
//console.log(socket);
}catch(e) {
console.log('ERROR OCURRED: ' + e);
}
if(socket !== undefined) {
socket.on('inventory list', function(data) { console.log(data); //i console but no response. });
}
</script>
</body>
</html>
Can you help me? I am extremely new in nodejs but I have some basic understanding. Or can you provide me a good example for this?
Thats all thanks.
In both, client and server, your are listening an event('inventory list'), but no one emits this event.
If you want to send the list to the client on conection you can try something like this on server:
io.on('connection', function(socket){
console.log('A user is connected!!');
socket.emit('inventory list', { list: 'mylist' });
socket.on('disconnect', function() {
console.log('user disconnected!');
});
});
http://socket.io/docs/server-api/
Related
I am trying through node js, express and mongoose to create a way to add the same mongoose Schema more than one time I want to use a trigger button. I have to restart the server to add more to the DB.
Later on I want to change it through a counter but first I need to get this working.
I am trying to solve it on my own but I got stuck, thank you for your help !
the app.js I use as server.
/app.js
const express = require('express');
const { default: mongoose } = require('mongoose');
const path = require('path');
const db = require("./database");
const app = express();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
app.use(express.static('DB'));
app.use('/Dev', express.static(path.join(__dirname, 'Dev', 'public')));
//Export function to new a .js file
var ClickyClicky = new mongoose.Schema({
name: {
type: String,
require: true
}},
{
timestamps: true, //time
}
);
var Clicky = mongoose.model('Click', ClickyClicky, 'clickystore');
var Clicks = new Clicky({ name: 'Test' });
//Export function to new a .js file
//Save button trigger.
app.post('/test', (req, res) => {
Clicks.save(function (err, book) {
if (err) return console.error(err);
console.log(book.name + " saved to bookstore collection.");
});
});
//Save button trigger.
app.post('/alfa', (req, res) => {
Clicks.save(function (err, name) {
if (err) return console.error(err);
console.log(name.name + " saved to name collection.");
});
});
// // 404 page
app.all('*', (req, res) => {
res.status(404).send('<h1>404, Page not found !</h1>');
});
app.listen(5000, () => {
console.log('Server started at http://localhost:5000');
});
/client.js
console.log('Client code running');
const testButton = document.getElementById('Button');
testButton.addEventListener('click', function(e) {
console.log('Butten was clicked');
fetch('/test', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
const testButton2 = document.getElementById('Button2');
testButton2.addEventListener('click', function(e) {
console.log('Butten was clicked');
fetch('/alfa', {method: 'POST'})
.then(function(response) {
if(response.ok) {
console.log('Click was recorded');
return;
}
throw new Error('Request failed.');
})
.catch(function(error) {
console.log(error);
});
});
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="Button">Click me for a test!</button>
<button id="Button2">Click me for a test1!</button>
</body>
<script src="./Dev/Client.js"></script>
</html>
\database.js
require('dotenv').config();
const mongoose = require('mongoose');
mongoose.set("strictQuery", false);
mongoose.connect(process.env.MONGOOB_URI, () => {
console.log("Connected to MongoDB");
});
I solved my issue with adding, unique: false to my mongoose schema and deleted the old input from the BD
Below is my server script. I want to show " a particular user has left the chat" by clicking leave button index.html which is emitting 'disconnect' event. But this doesn't seem to work. I guess it implies that default event can't be emitted. Plz help me do that. Any sort of help is appreciated.
socket.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection',function(socket)
{
//console.log("user connected")
socket.on('new user', function(data) {
console.log(data);})
socket.on('disconnect', function(data) {
console.log(data);
})
})
http.listen(3000, function(){
console.log('listening on *:3000');
})
index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<style>
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect();
//
$(function(){
$('#join').click(function(){
var name= $('input').val();
socket.emit('new user', name + ' has just joined the chat');
})
$('#leave').click(function(){
var name= $('input').val();
socket.emit('disconnect', name + ' has left the chat');
})
})
</script>
Choose your username <input type="text">
<button id="join" type="submit">
Enter
</button>
<button id="leave" type="submit">
Leave
</button>
</body>
try this
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
socket.on('new user', function(data) {
console.log(data)
})
socket.on('disconnect', function(data) {
console.log(data)
})
http.listen(3000, function(){
console.log('listening on *:3000');
})
}
I'm working on a simple Node.js bi-directional client\server communication channel and I'm attempting to use socket.io on the server and socket.io-client on the client.
I've inserted the code below, as you'll see it's pretty basic stuff, and I'm running both on my local machine - to minimise complexity.
The behaviour I'm seeing is:
I start the server.
The server logs 'Server started' to the console.
I start the client.
The client logs 'Server is ready!'
Nothing else happens...
What I'd expect is the server to log a 'Client is ready!' message and then the content ('Ready received').
I've even used WireShark to sniff the line and it does appear that the client is emitting the message, as designed - but the callback on the server isn't firing.
I'm running node v0.8.4 with express v3.1.0, socket.io v0.9.13 and socket.io-client v0.9.11 (all installed via npm).
Here's the server code...
var http = require('http'),
express = require('express'),
app = express(),
server = http.createServer(app);
app.configure(function(){
app.use(express.static(__dirname + '/public'));
});
server.listen(8080);
console.log("Server started");
var io = require('socket.io').listen(server);
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
And here's the client code...
var clientio = require('socket.io-client');
var socket = new clientio.connect('http://localhost', { port: 8080 });
socket
.on('server ready', function(data){
console.log('Server is ready!');
socket.emit('comms', 'Ready received');
})
.on('connect-error', function(error) {
console.log('Connection Error\n' + error);
})
.on('error', function(error) {
console.log('Socket Error\n' + error);
})
The documentation and examples for both socket.io and socket.io-client are somewhat confused (to be charitable) and they appear to be a bit of a moving target... but from what I can tell, I think this should work.
I'm hoping someone can give me advice as to where I'm going wrong?
In your server you have this code:
io.sockets
.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' }) ;
})
.on('comms', function(content) {
console.log('Client is ready!');
console.log(content);
});
What you should do is something like this:
io.sockets.on('connection', function(socket){
socket.emit('server ready', { msg: 'ready' });
socket.on('comm', function(content){
console.log('Client is ready!');
console.log(content);
});
});
hopefully this is doing more or less what you need it to do. Just a couple of minor changes.
app.js
var app = require('express')()
, server = require('http').createServer(app)
, io = require('socket.io').listen(server);
// using 'connect' to handle static pages
app.use(require('connect').static(__dirname + '/public'))
server.listen(8080);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.emit('server ready', { msg: 'ready' });
socket.on('comms', function(content) {
console.log(('Client is ready\n'));
console.log(content);
});
});
index.html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<script>
window.jQuery || document.write('<script src="js/jquery-1.8.3.min.js"><\/script>')
</script>
<script src="/socket.io/socket.io.js"></script>
</head>
<body>
<script>
(function (d, b) {
function bindEvents() {
function doSomething(msg) {
$.each(msg, function (key, value) {
console.log('doSomething...');
$("body").append("<p>" + value + "</p>")
});
};
// var socket = io.connect();
var socket = io.connect('http://localhost');
socket.on('server ready', function (msg) {
console.log('Server is ready!\n', msg);
doSomething(msg);
socket.emit('comms', {
msg: 'Client is Ready'
});
});
socket.on('connect-error', function (err) {
console.log('Connection Error\n', err);
});
socket.on('error', function (err) {
console.log('Connection Error\n', err);
});
};
$(document).ready(function () {
bindEvents()
});
})(jQuery, this)
</script>
I am new to Node and Socket.io and attempting to get the below code running. It is designed to service WebSocket requests, however I would like to amend it to also serve static content such as index.html.
My web socket code is as follows:
var http = require("http"),
sys = require("sys"),
io = require("socket.io"),
GlobTrie = require("glob-trie.js");
var Brokaw = {};
Brokaw.Server = function(port) {
var self = this;
// setup the basic HTTP server -- socket.io will wrap this
var server = http.createServer(function(req, res) {
// We have to respond with something, otherwise the connections hang :(
res.writeHead(404);
res.close();
});
server.listen(port);
this._io = io.listen(server, { "resource": "brokaw" });
this._trie = new GlobTrie();
this._io.on("connection", function(conn) {
new Brokaw.Server.Client(conn, self);
});
};
new Brokaw.Server(8080);
And my code to serve the index.html is as follows:
// Hardcode *all* HTTP requests to this server to serve up index.html
fs.readFile(
__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
}
);
Can anyone advise on how to integrate the two i.e. amend the top code to serve my index.html file also?
Appreciate any comments, and I have been struggling for many hours!
Regards, Ben.
There is an example, taken from the official Socket.IO homepage:
Server-side:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(80);
function handler (req, res) {
fs.readFile(__dirname + '/index.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
Client-side:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('news', function (data) {
console.log(data);
socket.emit('my other event', { my: 'data' });
});
</script>
I'm trying an example of WebSocket to develop a simple chat.
server.js:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, fs = require('fs')
app.listen(8080);
function handler (req, res) {
fs.readFile(__dirname + '/test.html',
function (err, data) {
if (err) {
res.writeHead(500);
return res.end('Error loading index.html');
}
res.writeHead(200);
res.end(data);
});
}
and test.html:
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost');
socket.on('connect', function() {
alert('<li>Connected to the server.</li>');
});
socket.on('message', function(message) {
alert(message);
});
socket.on('disconnect', function() {
alert('<li>Disconnected from the server.</li>');
});
function sendF(){
var message = "Test";
socket.send(message);
alert('Test Send');
}
In test.html I have also a simple button that onClick call sendF.
If I try it I see on my browser an alert when I CONNECT, SEND, and DISCONNCT, and if I check in console, I see the message.
But I cannot receive the same message in response from server, to show it in my browser! I think socket.on('message'... is not working for me!
Your server.js is missing event listeners. It's also missing where you are doing the send of the message to be displayed in the browser.
io.sockets.on('connection', function (socket) {
console.log('user connected');
socket.send('hello world');
socket.on('disconnect', function () {
console.log('user disconnected.');
});
socket.on('message', function (data) {
console.log(data);
});
});