Private chat using node.js and socket.io - javascript

Im tryng to create a private chat between a key using a node.js and socket.io,
the problem is when i emit a message, that message is not displayed on the room, and i dont know what is the problem...
SERVER
var app = require('express')();
var express = require('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.sockets.on('connection', function(socket){
console.log("step 0 OK"); // Works
socket.on('room', function (room) {
console.log("step 1 OK"); // Works
socket.join(room);
});
});
room = "1234";
//THIS CODE NOT WORKING
io.sockets.in(room).emit('message', 'what is going on, party people?');
http.listen(3000, function(){
console.log('listening on *:3000');
});
CLIENT
$(document).ready(function() {
var socket = io('http://localhost:3000');
$("#triggerBtn").on("click", function(e) {
e.preventDefault();
socket.emit('room', '1234');
return false;
});
socket.on('message', function(data) {
console.log("Step 2 OK"); //THIS CODE IS NOT EXECUTED
});
});
HTML
<html>
<head>
<title>Bootstrap Case</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.2.0.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
</head>
<body>
<div class="container-fluid">
<li><button type="button" class="btn btn-default" id="triggerBtn">Enviar</button></li>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="./bootstrapPage.js"></script>
</body>
</html>

Sockets can't emit without a connection. move:
io.sockets.in(room).emit('message', 'what is going on, party people?');
inside:
io.sockets.on('connection', function(socket){ ...

Related

I am getting io not defiend error in my socket.io client

This is my server side code for creating connection to the socket.I am using node.js code and using socket.io in that.
const path = require('path');
const http = require('http');
const express = require('express');
const socketIO = require('socket.io');
const port = process.env.PORT || 3000;
var app = express();
var server = http.createServer(app);
var io = socketIO(server);
io.on('connection', (socket) => {
console.log('New user connected');
})
and this is my client side code i am using plain javascript as a client and I am using 2.1.1 version of socket.io, I am getting io not defiend error,I am very new to socket.io please help me one this one.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0">
<meta charset="utf-8">
</head>
<body>
<script>
$(document).ready(function(){
var socket = io('http://localhost:3000');
console.log("Socket connected"+socket.connected);
socket.on('notification', function(value){
//insert your code here
});
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
</body>
</html>
Your first script (the one using io) is running before your other scripts (the jQuery and Socket scripts). Move your scripts around like so:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
<script>
$(document).ready(function() {
var socket = io('http://localhost:3000');
console.log("Socket connected" + socket.connected);
socket.on('notification', function(value) {
//insert your code here
});
});
</script>
As I'm new to web development this might be wrong, but I would try to place your script below the script where you import socket.io.js
In your function you are calling io but before you call it it doesn't seem to be declared.
Hope this works.

Unable to send data from one Client to another in socket.io Node.JS

I have two clients which can interchange some data over socket.io. I also have a server. What i need to do is i want to send data from client 1 to client 2 over a socket and i am unable to figure out that how i can achieve it.Please note that client 1 and client 2 are different html pages.
Server.JS
var express = require('express');
var app = express();
var fs = require('fs');
var path = require('path');
var server = require('http').createServer(app);
var io = require('socket.io')(server);
var port = process.env.PORT || 3000;
var ip=process.env.IP||"192.168.1.5";
app.use(express.static(__dirname));
server.listen(port,ip, function () {
console.log('Server listening at port %d ', port);
});
app.get('/index', function(req, res) {
res.sendFile(path.join(__dirname,'/test.html'));
})
app.get('/index1', function(req, res) {
res.sendFile(path.join(__dirname,'/test1.html'));
})
io.on('connection', function (socket) {
socket.on('broadcast', function (message) {
console.log(message);
socket.broadcast.emit('message', message);
});
console.log("connected");
});
Client1.JS
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script >
var socket = io.connect();
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
alert(data)
});
</script>
</body>
Client2.JS
<!doctype html>
<html lang="en">
<head>
</head>
<body>
<script src="/socket.io/socket.io.js"></script>
<script >
var socket = io.connect();
socket.on('message', function (data) {
alert(data)
//socket.emit('message',"Hello world");
});
</script>
</body>
Ok, here is what I did on my local and you may change it by your needs.
server.js
var io = require('socket.io')(80);
io.on('connection', function (socket) {
socket.on('broadcast', function (message) {
console.log(message);
socket.broadcast.emit('message', message);
});
console.log("connected");
});
client1.js
var socket = io.connect('ws://127.0.0.1');
socket.emit('broadcast',"Broadcasting Message");
socket.on('message', function (data) {
$('#client1').html(data);
});
client2.js
var socket = io.connect('ws://127.0.0.1');
socket.on('message', function (data) {
$('#client2').html(data);
});
index.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src='https://code.jquery.com/jquery-1.12.4.min.js'></script>
<script type="text/javascript" src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="client1.js"></script>
<script type="text/javascript" src="client2.js"></script>
</head>
<body>
<div> <h1> CLIENT 1 </h1><div id="client1"></div></div>
<div> <h1> CLIENT 2 </h1><div id="client2"></div></div>
</body>
</html>
On a termminal after you run, node server.js and reload your page, you will see client2 will have Broadcasting message html appended
Make sure to pass the URL to the server when instantiating WS on the client side... for example var socket = io.connect('http://localhost');
On the server side, each WS connection with each client is a unique instance. That is to say that for this purpose you must be deliberate about which WS connection you target when emitting events.
The first thing to solve is how to associate WS connection instances with specific clients. The answer to this is to use a map/dictionary/plain ol' javascript object with some sort of unique client identifier as the key and the instance of the WS connection as the value. Pseudo-code:
let connections = { 'client1': WSinstance, 'client2': WSinstance };
You would add to this object every time you create a new WS instance. Assuming you have a way to uniquely identify a client and that is stored in the variable clientId, you could do the following:
io.on('connection', function (socket) {
connections[clientId] = socket;
}
Now if you want to emit a message to just client1 you can use the WS instance associated with them by grabbing it from the object connections.client1 or if you want to target client2 connections.client2

Socket.io simple node app is not working

I have this little socket room app, but for a reason is not working. I'm trying to make the user join the room on click and display an alert, can't figure out the issue, I'm kinda new to sockets and can't even get this simple app working.. This is my code
////app.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) {
socket.on('room', function(room) {
socket.join(room);
});
});
room = "abc123";
io.sockets.in(room).emit('message', 'what is going on, party people?');
http.listen(3000, function(){
console.log('listening on localhost:3000');
});
////index.html
<!DOCTYPE html>
<html>
<head>
<title>flip</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>
<body>
<button>Join the room!</button>
</body>
<script>
var socket = io.connect();
// let's assume that the client page, once rendered, knows what room it wants to join
var room = "abc123";
socket.on('connect', function() {
$('button').click(function() {
socket.emit('room', room);
})
});
socket.on('message', function(data) {
alert(data)
});
</script>
</html>
On the client side you have to:
var socket = io.connect('http://localhost:3000');
On the server side:
io.on('connection', function(socket) {
socket.on('room', function(room) {
socket.join(room);
room = "abc123";
io.to(room).emit('message', 'what is going on, party people?');
});
});
You can not emit until you receive the connection.
You should instantiate a new instance of io, like so:
const socket = io();

Socket.io is not defined

Whenever I go to http://localhost:8080/search (search.html), it loads all of the html, then it reaches the client-side javascript and crashes. The first console.log in searchClient.js works, but not the second. The error is that io is not defined.
server.js:
var http = require('http');
var express = require('express');
var anyDB = require('any-db');
var engines = require('consolidate');
var app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server);
var conn = anyDB.createConnection('sqlite3://riverdata.db');
app.engine('html', engines.hogan);
app.set('views', __dirname + '/templates');
app.use(express.static(__dirname + '/public'));
app.get("/", function(request, response){
response.render('home.html');
});
app.get("/search", function(request, response){
response.render('search.html');
});
io.on('connection', function(socket){
socket.on('join', function(){
});
socket.on('search', function(toShowList, conditionsList){
var data = conn.query('SELECT toShowList FROM riverdata WHERE conditionsList');
console.log("im in socket.on(search)");
socket.emit('data', data);
});
socket.on('disconnect', function(){
});
});
app.listen(8080);
searchClient.js:
console.log("begins");
var socket = io.connect();
console.log("keeps running");
window.addEventListener('load', function(){
console.log("page loads");
var search = document.getElementById("searchButton");
submit.addEventListener("click", search, false);
socket.emit('join');
socket.on('data', function(data){
console.log(data);
})
}, false);
function search(){
console.log("button clicked");
var toShowList = [];
var conditionsList = [];
socket.emit('search', toShowList, conditionsList);
}
search.html:
<!DOCTYPE HTML PUBLIC>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src='localhost:8080/socket.io/socket.io.js'></script>
<script type="text/javascript" src="/searchClient.js"></script>
<title>Envirostats Database</title>
<link rel="stylesheet" href="/style.css" type="text/css" />
</head>
<body class="search">
<form action="">
<input type="checkbox" name="data" value="data"> Show Date <br>
<input type="checkbox" name="data" value="river"> Show River <br>
</form>
<button id=searchButton> Search </button>
</body>
</html>

Node.js socket.io with websocket

I'm begginer in Node.js or websocket. I have problem:
My HTML code:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<script>
"use strict";
var gniazdo = new WebSocket('ws://localhost:3000');
gniazdo.onopen = function(){
console.log('Połączono');
};
gniazdo.onmessage = function(m){
console.log(m.data);
};
</script>
</body>
</html>
My Node.js code:
var io = require('socket.io')(3000);
io.on('connection', function(socket){
console.log('a user connected');
});
I have error in console:
WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response
Help plz :)
Your client is using WebSockets, but Socket.IO has its own protocol (that may be transported over WebSockets, but it can also be transported over other protocols). Change your client to use Socket.IO's own client:
<script src="https://cdn.socket.io/socket.io-1.1.0.js"></script>
<script>
'use strict';
var gniazdo = io('ws://localhost:3000');
gniazdo.on('connect', function () {
console.log('Połączono');
gniazdo.on('message', function (m) {
console.log(m.data);
});
});
</script>

Categories

Resources