Hello guys i'm having a problem in redis pub/sub because my client does not show the message i've published in redis-cli. I used the codes found here in stackoverflow and i made some modification. Here is the link and code. I hope you can help me, my goal is to publish the message to the client index.html using redis publish in redis-cli. I've done this before but i can't make it work again. Thanks in advance guys.
Here is my client index.html
<html>
<head>
<title>PubSub</title>
<script src="/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
<!-- <script src="/javascripts/socket.js"></script> -->
</head>
<body>
<div id="content"></div>
<script>
var socket = io.connect('http://localhost:3000');
var content = $('#content');
socket.on('connect', function() {
});
socket.on('message', function (message){
content.prepend(message + '<br />');
}) ;
socket.on('disconnect', function() {
console.log('disconnected');
content.html("<b>Disconnected!</b>");
});
socket.connect();
});
</script>
</body>
</html>
Here is my server.js
var express = require('express');
var app = express();
var redis = require('redis');
var http = require('http');
var server = http.createServer(app);
var socket = require('socket.io').listen(server);
var publish = redis.createClient();
app.listen(3000);
console.log("Express server listening on port 3000")
app.get('/', function (req,res) {
res.sendfile(__dirname + '/public/index.html');
});
socket.on('connection', function (client) {
var subscribe = redis.createClient();
subscribe.subscribe('pubsub');
subscribe.on("message", function (channel, message) {
publish.send(message);
});
publish.on('message', function (msg) {
});
publish.on('disconnect', function() {
subscribe.quit();
});
});
Redis will not send data to connected clients for you. You must instruct Socket.IO to emit data:
subscribe.on("message", function (channel, message) {
socket.emit('message', message);
});
Related
I am very new to this socket.io.
I have the code this is a node server code:
var express = require("express");
var app = express();
var http = require("http").createServer(app);
var socketIO = require("socket.io")(http);
var socketID = "";
socketIO.on("connection", function (socket) {
console.log("User is conneected ", socket.id);
socketID = socket.id;
});
And here is the code for a ejs file:
......
<script src="/public/js/socket.io.js"></script>
<script>
......
var socketIO = io("http://localhost:3000");
......
</script>
......
And the socket.io.js file is here:
I tried but nothing is working. The same error pops whenever I refresh the page.
I am very new to this and I really want to get it sorted as soon as possible!!
I already have a listen function just after socket.on:
http.listen(3000, function () {
console.log("Server has started running!!");
.........................
.............
})
The below code is working for me.
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.sockets.on('connection', function (socket) {
console.log(socket);
})
server.listen(3000, function(){
console.log('listening on *:3000');
});
<script src="/socket.io/socket.io.js" > </script>
<script>
$(function () {
var socket = io.connect();
});
</script>
socket.io.js that you have mentioned is the same as that from the https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js... check the installed version of serail io in package.json and place the same version here in the path socket.io/2.2.0 it will work
Please Check versions of socket.io in your Frontend and Backend. It should be compatible. I had same issue so I solved it with version change. Like I had 2.2.0 in my frontend so I install 1.7.2 in backend or same as frontend.
so I have this idea in my head where when you run nodejs script it starts http(express) server on port 8080 and regular tcp(net) server on port 1337. And when you connect to tcp server via netcat and send "alert" it runs alert() command on webpage via javascript. Here is the code but the if statement is not working(it is printing data but not alerting on my web browser)
var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
var net = require("net");
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
var server = net.createServer();
io.on("connection", function(sock) {
console.log("Client connected");
server.on("connection", function(conn) {
var remoteAddress = conn.remoteAddress + ":" + conn.remotePort;
console.log("New client: " + remoteAddress);
conn.on("data", function (data) {
console.log(data.toString())
if (data.toString() == "alert") {
console.log("YES ALERT");
io.emit("HELLO");
}
});
conn.once("close", function () {
console.log(remoteAddress + " disconnected");
});
conn.on("error", function (error) {
console.log(remoteAddress + " Error: " + error);
});});
});
server.listen(1337, function() {
console.log("Listening on 1337");
});
http.listen(8080, function() {
console.log("Web server started on 8080");
});
Include socket io client js in your webpage and connect to socket server
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io('http://localhost:1337');
socket.on('connect', function(){});
socket.on('event', function(data){ alert(data.message) });
socket.on('disconnect', function(){});
</script>
you can Change the server side code, to emit the event to work with my example above.
io.emit("event",{"message":"HELLO"});
index.js
var app = require('express')();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
server.listen(process.env.PORT || 3000);
app.use(require('express').static(path.join(__dirname)));
console.log('server running');
app.get('/', function(req, res){
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
var addedUser = false;
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', data);
});
});
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
When I start up the server, the console logs "server running" fine. I can't get the submit post button to do anything. None of the debug console messages appear and nothing happens. It's supposed to emit "new post" when the submit button is clicked but it looks as if nothing goes through
I was able to get your code to work on my own computer like this:
index.js
var express = require('express');
var app = express();
var path = require('path');
var server = require('http').Server(app);
var io = require('socket.io')(server);
var users = [];
connections = [];
app.get('/', function(req, res){
res.sendFile(path.join(__dirname, 'index.html'));
});
app.use(express.static(__dirname));
console.log('server running');
io.on('connection', function (socket) {
console.log("connection");
socket.on('new post', function(post){
console.log(post);
socket.emit('posted', post);
});
});
server.listen(process.env.PORT || 3000);
client.js
$(function(){
function submit(){
socket.emit('new post', $("#text").val());
console.log("submitted");
}
function addPost(data){
console.log(2);
var $post = $('<p></p>').text(data);
console.log($post);
$("#posts").append($post);
}
$("#submit").on("click", function(){
submit();
});
socket.on('posted', function(data){
console.log(1);
addPost(data);
});
});
index.html
<html>
<head>
<title>title</title>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="text">Input</input>
<button id="submit">Submit</button>
<script src="/client.js"></script>
<br>
<br>
<br>
<div id="posts"></div>
<script>
var socket = io();
</script>
</body>
</html>
Changes to index.js
Define express variable so it can be reused.
Define app.get() before app.use(express.static(...)) so we're sure to serve index.html with the app.get() and not from the static location.
Change res.sendfile() to res.sendFile()`
Change socket.emit("posted", data) to socket.emit("posted", post).
Move server.listen() to end after everything else is set up.
Remove path.join() from express.static() call since it is not needed there.
Add path.join() to res.sendFile() call for cross platform safety in path building.
Of these, the only one I'm sure was causing an error was #4, the others are good housekeeping.
Changes to client.js
None
Changes to index.html
Change path to client.js to /client.js.
If this code doesn't work on heroku, then you either don't have files positioned in the right directories or heroku is not configured properly to allow your app or socket.io to work properly. If I were you, I would first verify that this code work on your own local computer and only then, go try it on heroku to eliminate variables first.
i am facing problem (i really frustrated), while i connecting the io.on function. i am using express,ioredis and socket.io. redis working properly but socket.io is not working. it is'nt working.please help.
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var Redis = require('ioredis');
var redis = new Redis();
//port connection
server.listen(3000);
console.log('server listening 3000');
//redis sub (working fine)
redis.subscribe('test-channel', function () {
console.log('Redis: test-channel subscribed');
});
//this code is not working (stop execution)
io.on('connection', function(socket){
console.log("new client connected");
});
io.on('connection', function (socket) {
console.log("new client connected");
redis.subscribe('message');
console.log("redis start");
//send message to frontend
redis.on("message", function(channel, message) {
console.log("mew message in queue "+ message + "channel");
socket.emit(channel, message);
});
//close socket
socket.on('disconnect', function() {
redis.quit();
console.log('redis disconnected!');
});
});
Client side
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.3.4.js"></script>
<script>
var socket = io.connect('http://localhost:3000');
socket.on('message', function (data) {
$(".progress-bar").css('width',+data+'%');
alert('connection established');
$("#messages").append( "<p>"+data+"</p>" );
});
</script>
Server side
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server); // it was require('socket.io')(server);
server.listen(3000);
Client side
io.sockets.on('connection', function(socket){
console.log("new client connected");
});
const { Server } = require("socket.io")
const io = new Server(server)
This question has already been answered, but I can't understand it at all. You can find it at this link.
socket.on calls its callback too many times
I have the same problem as this fellow. I'm attempting to make a chat program with socket.io, but when more than one user joins, each message outputs the number of times of how many users have been connected.
For example, when one user is connected, and he submits a message. It outputs once. When two users are connected, each of their messages output twice.
When three users are connected, each of their messages output three times.
Here is my client side code:
$('document').ready(function() {
var server = io.connect('http://localhost:8888');
$('.chat').keydown(function(event){
var save = this;
if(event.which == 13){
server.emit('message', $(save).val());
$(save).val('');
return false;
}
});
server.on('incoming', function(message){
$('#textfield').append("<p>" + message + "</p>");
});
});
Here is my server side code:
var socket_io = require('socket.io').listen(8888).sockets;
socket_io.on('connection', function(socket){
socket.on('message', function(message){
socket_io.emit('incoming', message)
});
});
Thank you!
You can use socket.broadcast.emit() to send to everyone except that socket:
var io = require('socket.io')(8888);
io.on('connection', function(socket) {
socket.on('message', function(message) {
socket.broadcast.emit('incoming', message);
});
});
UPDATE: The following example works just fine for me:
server.js:
var app = require('http').createServer(handler);
var io = require('socket.io')(app);
var 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.on('connection', function(socket) {
socket.on('message', function(message) {
socket.broadcast.emit('incoming', message);
});
});
index.html:
<html>
<head>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$('document').ready(function() {
var server = io.connect('http://localhost');
$('.chat').keydown(function(event) {
if (event.which == 13) {
var $save = $(this);
server.emit('message', $save.val());
$save.val('');
return false;
}
});
server.on('incoming', function(message){
$('#textfield').append("<p>" + message + "</p>");
});
});
</script>
</head>
<body>
<input type="text" class="chat">
<div id="textfield"></div>
</body>
</html>
When pressing enter, the message in the input box is only displayed once to all other connected socket.io users.
Okay, I've finally figured out the problem.
I'm using Express 4.0. That means, I'm using routes to run the server, and I had the socket io code running inside the route. Each time a user connects, it has to go through the route first, and it's all binding onto the same socket_io.
Thanks to everybody who helped!
I also faced it, like multiple socket calls in network tab and i just add this "transports" key object to socket instance, both on client and backend.
socket = io("http://localhost:3002", {
transports: ['websocket']
})
React, Node, AWS EB