Socket.io not connecting (2) - node.js

I'm using Laravel and my directory structure is like below:
/example.com
/server.js
/node_modules
/css
/js
/main/views/writemessage.blade.php
/main/views/socket.blade.php
/main/app/Http/Controllers/SocketController.php
my code in server.js is:
var app = require('express')();
var server = require('http').Server(app);
var io = require('socket.io')(server);
io.set('origins', '*:*');
var redis = require('redis');
var cors = require('cors');
app.use(cors());
server.listen(8890);
io.on('connection', function (socket) {
console.log("new client connected");
var redisClient = redis.createClient();
redisClient.subscribe('message');
redisClient.on("message", function(channel, message) {
console.log("mew message in queue "+ message + "channel");
socket.emit(channel, message);
});
socket.on('disconnect', function() {
console.log('Disconnected!!!');
redisClient.quit();
});
});
my code in writemessage.blade.php is:
#extends('_template.default')
#section('main-content')
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script>
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2" >
<div id="messages" ></div>
</div>
</div>
</div>
<script>
var socket = io.connect('https://example.com:8890', {secure: true});
socket.on('message', function (data) {
console.log('YES!!!!!!!!!!');
$( "#messages" ).append( "<p>"+data+"</p>" );
});
</script>
#endsection
my code in socket.blade.php is:
#extends('_template.default')
#section('main-content')
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Send message</div>
<form action="sendmessage" method="POST">
<input type="text" name="message" >
<input type="submit" value="send">
{{csrf_field()}}
</form>
</div>
</div>
</div>
</div>
#endsection
When I was in Windows it was returning CORS issues, but now when I'm using Linux it doesn't return that error but it doesn't return anything in console.
Also redis is running...but when I run node server.js it doesn't even print Connected nor Disconnected messages in console. Where my problem is from? Is it from url? I say url because when I check the Network Monitor in firefox I see that it is saying The connection used to fetch this resource was not secure. Have I done something wrong? Or should I do something more? How can test where the problem is from?
BTW my node version: 6.14.3 and my npm version: 3.10.10
Thanks

Related

Is there is any solution for connecting client and server in socket program in node js

I am trying to connect socket client and server but not able. This is my server expServer.js
var path = require('path');
var express = require('express');
var app = express();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.use(express.static(path.join(__dirname,'css')));
io.on('connection', (socket) =>{
console.log("new user");
socket.emit("msg","hello");
});
http.listen(8000,()=>{
console.log("server is running at port 8000");
});
another file index.html
<html>
<head>
<script defer src="Client/client.js"></script>
<script defer src="http://localhost:8000/socket.io/socket.io.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<nav>
<img class="logo" src="logo.png" >
</nav>
<div class="container">
<div class="message left">harry:hi how are you?</div>
<div class="message right">rohan:vai i am good.How about you?</div>
</div>
<div class="send">
<form action="#" id="send-contaner">
<input type=" text" name="messageid" id="messageid">
<button type="submit" class="btn">Send</button>
</form>
</div>
</body>
</html>
another file client.js
var socket = io("http://localhost:8000");
socket.on("msg", data =>{
console.log(data);
});
I am not able to connect client and server. I got error "Uncaught ReferenceError:io is not define"
I hope somebody have solution.
Your script sequence:
<script defer src="Client/client.js"></script>
<script defer src="http://localhost:8000/socket.io/socket.io.js"></script>
Try changing the sequence to
<script defer src="http://localhost:8000/socket.io/socket.io.js"></script>
<script defer src="Client/client.js"></script>
For your reference you can check this:
https://github.com/abhishekpankar/socket-io

Not able to access port in linux machine but able to access from windows, using nodejs & angular js

When running node & angularjs project on my windows by giving listen port, it's running.
But at the same time when the same code is run on Linux machine port is inaccessible.
I have tried commands,
node node.js
node node.js --port 8952 --host 0.0.0.0 --disableHostCheck true
but it didn't work for Linux VM
please suggest needing full changes. Thanks..!!
Angular.js
<body ng-app="myApp">
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<link rel="stylesheet" type="angular/css">
<div style="text-align: center">
<h1 style="color: cornflowerblue"><b>Angular MVN ArchType</b></h1></div>
<div ng-controller="myCtrl">
<br>
<div style="margin-left: 40%">
<input type="text" ng-model="par1">
<button class="button" ng-click="myFunc()"><b>GET</b></button>
<br>
<br>
</div>
<div>
<div style="margin-left: 30%">
<textarea style="width: 500px;height: 500px">{{data}}</textarea>
</div>
</div>
</div>
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) {
$scope.myFunc = function () {
$http({
method: 'GET',
url: './fetch/',
params: {"id": $scope.par1},
})
.success(function (data, status) {
console.log(data);
$scope.data = data;
})
.error(function (data, status) {
alert("Error in scripting angular");
});
};
});
</script>
</body>
Node.js
var express = require('express'),
app = express();
var bodyParser = require("body-parser");
app.use(bodyParser.json()); // support json encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
const child_process = require('child_process');
app.get('/fetch', function(req,res){
console.error('hello inside node ');
var id = req.query.id;
console.log("In progressss...........");
child_process.exec('echo hello ' + id, function (error, stdout, stderr) {
res.send(stdout.toString());
});
});
app.get('/', function(request, response){
response.sendfile('index.html');
});
app.listen(4378);
console.log('Rest Demo Listening on port 4378');

nodejs terminal:console.log can't print

app.js
app.get('/',function(req,res){
res.sendfile(__dirname + '/index.html');
console.log('hhh');
});
io.sockets.on('connection',function(socket){
socket.on('nickname',function(data){
console.log('The sever received the following nickname: ' +data);
});
});
index.html
<h1>Socket.IO Express Example</h1>
<form id="set-nickname">
<label for="nickname">Nickname:</label>
<input type="text" id="nickname">
<input type="submit" value="submit">
</form>
<script src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript">
var socket = io.connect();
jQuery(function($){
var nickName = $('#nickname');
var setNacknameForm = $('#set-nickname');
setNacknameForm.submit(function(event){
event.preventDefalut();
socket.emit('nickname',nickName.val());
});
});
</script>
hhh can print in terminal browser but I enter words in browser, I click submit, nothing is printed in terminal.
I'm using express version 4.x
What should I do?

Socket.io failing to log chat message in console

I'm walking through the Socket.io tutorial on creating a chat room, and I'm having trouble getting my app to log the chat message to the console.
The app is logging when a user connects & disconnects, but it is not logging when a message is passed through.
Any thoughts?
The relevant parts of my index.html page:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
</script>
<body>
<ul id="messages"><ul>
<form action="">
<input id="m" autocomplete="off" /><button>Send</button>
</form>
</body>
My index.js file:
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(express.static('public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
socket.on('disconnect', function(){
console.log('user disconnected');
});
socket.on('chat message', function(msg) {
console.log("message: " + msg);
});
});
I've gotten it to work!
Steps to solution:
- separate the script tag with the event listener into a separate JS file
- include that JS file in the same place the script tag was originally
- load the chatListener when the document is ready
My files now look like this and everything works beautifully:
index.html:
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script src="main.js"></script>
<body>
<ul id="messages"><ul>
<form action="">
<input class="chat" id="m" autocomplete="off" />
<input class="btn" type="submit" value="Send" />
</form>
</body>
index.js: nothing changed
main.js:
var socket = io();
var chatListener = function() {
$('form').submit(function() {
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
}
$(document).ready(function() {
chatListener();
})
In the end, I think it was a beginner's JS mistake; I was loading the script at the top of the page (as the tutorial suggested), and the event listener on the form was never registering.

Redis Cookbook Chat Recipe

I am a new starter to Node.Js and Redis. I got the Redis cookbook and was trying out the Chat client & Server recipe.
I was wondering if anybody got the code to work or if there is some bug in the code.
I dont see where the sent messages from the client get invoked on the server.
Any help would be great.
Regards,
Tom
Client Code:
<?php
?>
<html>
<head>
<title></title>
<script src="http://192.168.0.118:8000/socket.io/socket.io.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script>
var socket = io.connect('192.168.0.118',{port:8000});
socket.on('message', function(data){
alert(data);
//var li = new Element('li').insert(data);
//$('messages').insert({top: li});
});
</script>
</head>
<body>
<ul id="messages">
<!-- chat messages go here -->
</ul>
<form id="chatform" action="">
<input id="chattext" type="text" value="" />
<input type="submit" value="Send" />
</form>
<script>
$('#chatform').submit(function() {
socket.emit('message', 'test'); //$('chattext').val());
$('chattext').val(""); // cleanup the field
return false;
});
</script>
</body>
</html>
Server Code:
var http = require('http');
io = require('socket.io');
redis = require('redis');
rc = redis.createClient();
//rc1 = redis.createClient();
rc.on("connect",function(){
rc.subscribe("chat");
console.log("In Chat Stream");
});
rc.on("message",function (channel,message){
console.log("Sending hope: " + message);
//rc1.publish("chat","hope");
socketio.sockets.emit('message',message);
});
server = http.createServer(function(req,res){
res.writeHead(200,{'content-type':'text/html'});
res.end('<h1>hello world</h1>');
});
server.listen(8000);
var socketio = io.listen(server);
It looks like you're not listening for any connect / message events from socket.io.. try something like
socketio.sockets.on('connection', function(socket) {
console.log("Got connection");
socket.on('message', function(msg) {
rc1.publish("chat", msg);
});
});
You'll need to uncomment your rc1 up there, you will need that second redis connection

Resources