socket.io communication between two different client side js files - javascript

I have the following code in file1.html:
<body>
<button type="button" id="accept" value="accept">Accept</button>
<script>
var socket = io.connect('http://localhost:4000');
// Query DOM
var acceptButton=document.getElementById('accept');
// Emit events
acceptButton.addEventListener('click', function(){
socket.emit('notification', {
message: acceptButton.value,
});
});
module.exports=socket;
</script>
</body>
In file2.html:
<body>
<div id="notifications">
<h1>Your notifications here</h1>
</div>
<script>
var socket=require('/file1.html');
var notification=document.getElementById('notifications');
socket.on('notification', function(data){
notification.innerHTML+='<p> the event was accepted<p>';
});
</script>
</body>
Nodejs server code:
var server=app.listen(4000,()=>{
console.log('listening at port 4000');
})
var io=socket(server);
//connection to socket (backend)
io.on('connection',function(socket){
console.log('socket connection made',socket.id);
socket.on('notification', function(data){
console.log(data);
io.sockets.emit('notification', data);
});
});
I am a newbie to socket.io .I want to send the data from file1.html and receive data from file2.html. I don't think there is any mistake in the server code. I am doubtful only in the html files. How do I solve it?

Related

Socket.io in javascript gives NOT_RESOLVED error

I need to connect HTML website to node server chat application. HTML client side has some HTML files and javascript file.I need to connect socket.io chat server using javascript. So it needs to initialize socket.io port inside javascript.
I have created socket.io chat server in node.js using javascript it is working fine. And I need to call that node server using javascript client site.
It should initialize and socket server connect. It should able to emit and receive messages from the server site.
I have a socket.io backend service which is working fine. Because I test it with nodeJS client application. But I need it to use existing HTML web site which is not nodeJS
I have searched on google and can't find any website which is about connecting sockt.io using a javascript file. All tutorials are using nodeJS.
When I used
var io = require('socket.io').listen(server);
inside the javascript file and open HTML page in the browser, it throws an error.
This is my code, I got this from the internet I was trying to connect this implement my real code.
<!DOCTYPE html>
<html>
<head>
<link href="style.css" rel="stylesheet">
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
// socket.io specific code
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message(from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>
Error in the front end:
Uncaught ReferenceError: io is not defined
at chat-footer.html:10
This is my folder structure:
var io = require('socket.io').listen(server); should be on the server side. var socket=io(); should be in the client side javascript. If you are putting var io in the client side then you would get an error. Plus you need to link the socket io library in the <head> tag of the HTML: <script src='/socket.io/socket.io.js'></script>. If you do not have the library linked the io() function will not work. I hope that this solves your problem.
UPDATED
According to your code. You never defined the io(); function. You went ahead in the front end and said var socket = io.connect(). You never said what io is. What it should be is name a different variable var socket = io(); and then use var connector = io.connect().
SECOND UPDATE
If the html page is not being served from the nodejs backend, you will not be able to use socketio as it is not connected to a server. You need to serve the html page from the backend and use socketio on the same backend server.
I have resolved the error. The reason was I cannot add a socket.io reference directly because it's nodeJS script. So I added socket.io.js from nodeJS service library. By adding that my HTML page will directly refer running nodeJS server socket.io.js file.
This is my working and complete code to connect socket.io nodeJS server.
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script src="http://localhost:8000/socket.io/socket.io.js"></script> // add this line
<script>
var socket = io.connect('http://localhost:8000');
socket.on('connect', function () {
$('#chat').addClass('connected');
});
socket.on('announcement', function (msg) {
$('#lines').append($('<p>').append($('<em>').text(msg)));
});
socket.on('nicknames', function (nicknames) {
$('#nicknames').empty().append($('<span>Online: </span>'));
for (var i in nicknames) {
$('#nicknames').append($('<b>').text(nicknames[i]));
}
});
socket.on('user message', message);
socket.on('reconnect', function () {
$('#lines').remove();
message('System', 'Reconnected to the server');
});
socket.on('reconnecting', function () {
message('System', 'Attempting to re-connect to the server');
});
socket.on('error', function (e) {
message('System', e ? e : 'A unknown error occurred');
});
function message(from, msg) {
$('#lines').append($('<p>').append($('<b>').text(from), msg));
}
// dom manipulation
$(function () {
$('#set-nickname').submit(function (ev) {
socket.emit('nickname', $('#nick').val(), function (set) {
if (!set) {
clear();
return $('#chat').addClass('nickname-set');
}
$('#nickname-err').css('visibility', 'visible');
});
return false;
});
$('#send-message').submit(function () {
message('me', $('#message').val());
socket.emit('user message', $('#message').val());
clear();
$('#lines').get(0).scrollTop = 10000000;
return false;
});
function clear() {
$('#message').val('').focus();
};
});
</script>
</head>
<body>
<div id="chat">
<div id="nickname">
<form id="set-nickname" class="wrap">
<p>Please type in your nickname and press enter.</p>
<input id="nick">
<p id="nickname-err">Nickname already in use</p>
</form>
</div>
<div id="connecting">
<div class="wrap">Connecting to socket.io server</div>
</div>
<div id="messages">
<div id="nicknames"></div>
<div id="lines"></div>
</div>
<form id="send-message">
<input id="message">
<button>Send</button>
</form>
</div>
</body>
</html>

get() method or function

Unresolved function or method get().
I'm new in js and node and I got stuck with this while trying to make a chat using sockets. Here is the code:
.js
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
server.listen(8888);
app.get('/', function (req, res) {
res.sendFile(__dirname + '/index.html');
});
io.sockets.on('connection', function (socket) {
socket.on('send message', function (data) {
io.sockets.emit('new message', data);
});
});
.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>glupi chat</title>
<style>
#chat{
height: 500px;
}
</style>
</head>
<body>
<div id="chat"></div>
<form id="send-message">
<input size="35" id="message">
<input type="submit">
</form>
<script src='jquery-3.2.1.js'></script>
<script src="/socket.io/socket.io.js"></script>
<script>
$document.ready(function () {
var socket = io.connect();
var $messageForm = $('#send-message');
var $messageBox = $('#message');
var $chat = $('#chat');
$messageForm.submit(function (e) {
e.preventDefault();
socket.emit('send message', $messageBox.val());
$messageBox.val('');
});
socket.on('new message', function (data) {
$chat.append(data + "<br/>");
});
});
</script>
</body>
</html>
I'm using IntelliJ IDEA, I have every module and library that I need installed.
It appears that you have no route for the jQuery file you specify with this:
<script src='jquery-3.2.1.js'></script>
A nodejs express server does not server ANY files by default so unless you have a general purpose route for your static files or a specific file for that jQuery file, your express server will not know how to serve that file when the browser requests it.
You have several possible choices for how to fix that:
Change the jQuery URL in the script tag in your web page to point to one of the public CDNs for jQuery. There are often performance advantages to doing this. For example, you could change to this: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>.
Use express.static() on your server to configure a directory of static assets that will be automatically served by express when requested by the browser.
Create a specific route for the jQuery file just like you did with your exist app.get('/', ...)that responds to the/` GET request.

Can' call Socket.on() in nodeJS

I want to use nodeJS in my PHP web app. I followed the nodejs tutorial and that works fine when I run on localhost:3000 but I want to run on url like this localhost/final/chat/chat_index.html file. So What I did is following code
chat_index.html
<div id="newUser">
<form id="user">
<input id="username">
<input type="submit">
</form>
</div>
$(document).ready(function(){
var socket = io.connect('http://localhost:3000/final/chat/chat_index.html',
{resource:'https://cdn.socket.io/socket.io-1.2.0.js'});
$('#user').submit(function(){
socket.emit('new user', $('#username').val());
});
}); // document.ready ends here
</script>
index.js This is server side JS file
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/final/chat/chat_index.html', function(req, res){
res.sendFile(__dirname + '/chat_index.html');
});
io.on('connection', function(socket){
console.log('connected user');
socket.on('new user', function(user){
console.log(user);
});
});
http.listen(3000, function(){
console.log('listening to port');
});
Above chat_index.html page loads which shows the form on it. When I submit some data through this form server side js is not getting the data.
Is something missing in my code or I am doing something wrong in my code.
Thanks in advance
If you wish to run socket on an specific route, you can use room/namespace
http://socket.io/docs/rooms-and-namespaces/#
Example ( server )
var finalChat = io.of("/final/chat");
finalChat.on('connection', function(socket){
console.log('connected user');
socket.on('new user', function(user){
console.log(user);
});
});
If you want Independence private chat rooms, you may want to use id base socket rooms
Which version of express are you using? I believe in express 4 it should be:
var http = require('http').createServer(app);
On the client side could you also try using:
var socket = io.connect();
then load the resource in as a script tag?

Show random numbers on html sent from Node.js

I am trying to show random numbers generated in node.js to a file called display.html and show on port 3000. When I run the node code in server.js I get confirmation that data is being transmitted, but I see nothing on localhost:3000. I am using node.js express version 4.7.1 and socket.io version 1.0.6.
Thanks in advance!
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendfile('display.html');
});
io.on('connection', function(socket){
console.log('a user connected');
});
setInterval(function(){
console.log('emitting');
io.emit('coordinate', {
x: Math.random(),
y: Math.random(),
z: Math.random()
});
}, 3000);
http.listen(3000, function(){
console.log('listening on *:3000');
});
Here is the html where I take in the data:
<html>
<body>
<ul>
</ul>
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io('192.734.....:3000');
socket.on('coordinate', function(obj){
$('ul').append($('<li>').text(JSON.stringify(obj)));
});
oncoording
io.emit('coord'.., obj)
</script>
</body>
</html>
Try to change your HTML for this:
<html>
<body>
<ul>
</ul>
<script src="https://cdn.socket.io/socket.io-1.0.6.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io('127.0.0.1:3000');
socket.on('coordinate', function(obj){
$('ul').append($('<li>').text(JSON.stringify(obj)));
});
</script>
</body>
</html>
Tha last two lines of script is throwing a syntax error on browser:
oncoording
io.emit('coord'.., obj)

Socket Failed to load resource server (404 error)

hey guys m using to files for server side server.js and at client side using javascript
server.js
var express = require("express");
var io = require("socket.io").listen(app);
var app = express.createServer("localhost");
app.listen(3000);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/hello.html');
});
console.log("before");
io.sockets.on("connection", function (socket) {
console.log("after");
socket.on("message send", function (data) {
io.sockets.emit("new mesage", data);
});
});
and at client side using one html page name
hello.html
<html>
<head>
<style>
#chat{
height : 500px;
}
</style>
</head>
<body>
<div id="chat" > </div>
<form id ="send message">
<input id="message" type="text" ></input>
<input type="submit"></input>
</form>
<script type= "javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="/socket.io/socket.io.js"></script>
<script>
jQuery(function($){
var socket =io.connect();
var $messageForm = $("#send message");
var $messageBox=$("#message");
var $chat = $("#chat");
$messageForm.submit(function(e){
e.preventDefault();
socket.emit("message send" , $messageBox.val());
});
socket.on("new message", function(data){
$chat.append(data + "</br>");
});
});
</script>
</body>
</html>
when m start server then its proporly working but when i sent a request then it shows error like given blow
Failed to load resource: the server responded with a status of 404 (Not Found) /socket.io/socket.io.js
Uncaught ReferenceError: jQuery is not defined
versions
socket.io:0.9.16
exparess:3.4.0
thanks for your time :)
You need to bind the socket.io to the http server not the application server. Changes this to below..
var express = require('express'),
app = express(),
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
Refer Express guide for more info.
EDIT
To correct the Jquery error..
replace
jQuery(function($){
with
$(document).ready(function($)

Categories

Resources