my problem between socket.io and HTML5
Javascript Server:
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendfile('index.html');
});
io.on('connection', function (socket) {
socket.emit('news', 'Hello');
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
HTML5:
<html>
<head>
<meta charset="UTF-8">
<title>My Title</title>
</head>
<body>
<input type="button" id="getButton" value="Get Rooms">
<script src="/socket.io/socket.io.js"></script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
var socket = io();
$("#getButton").click(function () {
socket.on('news', function (data) {
alert(data);
});
});
</script>
</body>
</html>
When I click on the button (ID: getButton) I don't get an alert. The server ist working and I can access the page without any problems.
I am currently a newbie in socket.io/javascript (installed yesterday), if you have good informative pages about socket.io please post the link under this topic, thanks.
best regards
You're emitting the news message as soon as you connect, so it has already fired by the time you click your button. Try changing your code to this and you should see your alert:
var socket = io();
socket.on('news', function(data) {
alert(data);
});
You could trigger the event on a button with something like this:
Server:
io.on('connection', function(socket) {
//socket.emit('news','Hello');
});
// Return the news when it's requested
io.on('giveMeNews', function(socket) {
socket.emit('news', 'Here is your news');
});
Client:
// Listen for the news message
socket.on('news', function(data) {
alert(data);
});
// Request news from the server
$("#getButton").click(function() {
socket.emit('giveMeNews');
)};
Related
I want to be able to write functions in multiple .js files and use the same socket that is create in my main server.js
server.js:
var express = require('express')
var app = express()
var http = require('http')
var server = http.createServer(app)
var io = require('socket.io')(server)
var GOR = require('./gor')
var path = require('path');
app.use(express.static(path.join(__dirname, '/public')));
//handles get request and serves index.html
app.get('/', function(req, res) {
res.sendFile(__dirname + '/public/index.html');
});
//wait for server to start
server.listen(8080,()=>{
console.log("server started");
setInterval(emit_data,5000);
emit_data();
//setInterval(GOR.send_from_another_js,5000);
//GOR.send_from_another_js(io);
})
function emit_data(){
io.emit( 'update', "webserver.js");
}
As you can see from the code above, I have a function that emits to socket every 5 seconds and that works fine. I have confirmed it already.
All I want to do now, is to create a seperate.js file and keep all my functions there to make the code look cleaner. I name another .js file gor.js:
gor.js:
//I want to call this function in my webserver.js and transmit this socket
function send_from_another_js(io){
console.log("function called");
io.emit( 'update', "another_js");
}
module.exports = {
send_from_another_js
}
When I call this function in my server.js , it does not work:
server.listen(8080,()=>{
console.log("server started");
setInterval(GOR.send_from_another_js,5000);
GOR.send_from_another_js(io);
})
What is correct way to use the same .io in other .js files? The above does not work.
EDIT1
In my .html, I wait for a message on socket:
window.addEventListener('DOMContentLoaded', () => {
socket.on('update', function(number_to_set) {
console.log("socket update received");
document.getElementById('number1').innerHTML = number_to_set;
});
var button = document.getElementById("operation_code_button");
button.addEventListener("click", function(event){
var val = document.getElementById("operation_code_input").value;
console.log("socket clicked, emmiting data");
socket.emit('button_click',val);
});
})
And in my .js file I emit to this socket every 5 seconds:
server.listen(8080,()=>{
console.log("server started");
setInterval(emit_data,5000);
emit_data();
})
After 5 seconds, I can see that my webpage update data so everything works!!!
I want to declare the emit_data function inside another .js file and use it in my main .js file.
The function in my secondary .js file ( gor.js):
function send_from_another_js_1(io){
io.emit( 'update', data);
}
I want to call it in my main .js the same way I call emit_data
You need to wait for your server to get initialized. You are calling your function before socket.io is ready. That's why io.emit function is 'undefined'.
server.listen(8080,()=>{
GOR.send_from_another_js(io);
})
Edited:(3)
Trust it is what you are looking for...
"server.js"
const content = require('fs').readFileSync(__dirname + '/index.html', 'utf8');
const httpServer = require('http').createServer((req, res) => {
// serve the index.html file
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(content));
res.end(content);
});
const io = require('socket.io')(httpServer);
const apple = require("./File2.js")
apple.send_from_another_js_1(io);
apple.send_from_another_js_2(io);
var port = 3000; //wamp server
var prompt = 'Open browser at http://localhost:'
httpServer.listen(port, () => {
console.log(prompt, port);
});
"File2.js"
function send_from_another_js_1(io){
io.on('connection', function (socket) {
socket.on('file2_1_EventTrigged', function (data) {
socket.emit('update1', "send_from_another_js_1(io) : "+ data);
console.log("+++ function send_from_another_js_1(io) called");
});
});
}
function send_from_another_js_2(io){
io.on('connection', function (socket) {
socket.on('file2_2_EventTrigged', function (data) {
socket.emit('update2', "send_from_another_js_2(io) : "+ data);
console.log("... function send_from_another_js_2(io) called");
});
});
}
module.exports = {
send_from_another_js_1,
send_from_another_js_2
}
"index.html"
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Content-Type" content="text/html">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="keywords" content="HTML, CSS, JavaScript">
<meta name="author" content="Dr.Chaiya Tantisukarom">
<meta http-equiv="Cache-Control" content="public, max-age=31536000">
<title>NodeJS socket.io</title>
</head>
<body>
<h1 style="text-align: center;">Hello another world</h1>
<div style="text-align: center;">
<span>
<button onclick="file2_1()">file2_1</button>
</span>
<span>
<button onclick="file2_2()">file2_2</button>
</span>
</div>
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('connect',()=>{
//alert('Connected');
})
function file2_1(){
socket.emit('file2_1_EventTrigged', "Hello file2_1, how are you today?");
}
socket.on('update1', (data)=>{
alert(data);
})
function file2_2(){
socket.emit('file2_2_EventTrigged', "Hi file2_2, trust you are ok.");
}
socket.on('update2', (data)=>{
alert(data);
})
</script>
</body>
</html>
Cheers !!!
When you call this:
server.listen(8080,()=>{
console.log("server started");
setInterval(GOR.send_from_another_js,5000);
GOR.send_from_another_js(io);
})
setInterval() isn't providing a parameter for GOR.send_from_another_js(), so io becomes undefined.
To fix this, I would use a second lambda expression inside of your setInterval() call.
server.listen(8080, () => {
console.log("server started");
setInterval(() => {
GOR.send_from_another_js(io);
}, 5000);
GOR.send_from_another_js(io);
});
I am trying to output a message of 'XYZ is typing' whenever a user begins typing but I can't seem to fix my code. I feel as if the 'socket.broadcast.emit' in the App.JS of my code is the issue but I am not sure. If possible can somebody point me in the right direction to helping me fix my chat app. Thanks in advance!
Index.HTML
<!doctype html>
<html>
<head>
<title>Chit Chat</title>
<link rel="stylesheet" href="/css/styles.css">
</head>
<body>
<ul id="messages"></ul>
<div id="typing"></div>
<form action="">
<input id="username" placeholder="Username" type="text" />
<input id="message-box" autocomplete="off" type="text" placeholder="Type Message" />
<button id="button">Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script src="/js/scripts.js" charset="utf-8"></script>
</body>
</html>
App.JS (Server)
var express = require('express');
var app = require('express')();
var bodyParser = require('body-parser');
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}))
app.use(express.static('./public'));
app.get('/', function(req, res){
res.sendFile(__dirname + '/views/index.html');
});
var port = process.env.PORT || 3000;
http.listen(port, function(){
console.log('listening on ' + port);
});
// Socket.io
io.on('connection', function(socket) {
// when the client emits 'new message', this listens and executes
socket.on('new message', function(data) {
// we tell the client to execute 'new message'
io.sockets.emit('new message', data);
});
// when the client emits 'typing', we broadcast it to others
socket.on('typing', function(data){
socket.broadcast.emit('typing', data);
});
});
Scripts.JS
console.log('Loaded');
var socket = io();
$(function (){
chat();
emitEvents();
isTyping();
});
function chat() {
$('form').submit(function(e){
var message = {
username: $('#username').val(),
message: $('#message-box').val()
}
e.preventDefault();
socket.emit('new message', message);
$('#message-box').val('');
});
}
function isTyping() {
$('#message-box').keypress(function() {
socket.emit('typing', $('#username').val());
});
}
function emitEvents() {
socket.on('typing', function(data){
console.log(data);
$('#typing').append($('<p>').text(data + 'is typing'));
});
socket.on('new message', function(data){
$('#messages').append($('<li>').text(data.username + ': ' +
data.message));
});
}
I tried your code and it's working. I have created a live example.
I made 2 modifications in scripts.js, so the typing message will appear only once during the typing.
function emitEvents() {
socket.on('typing', function(data){
console.log(data);
$('#typing').html($('<p>').text(data + ' is typing')); // update
});
socket.on('new message', function(data){
$('#typing').html($('<p>').text('')); // update
$('#messages').append($('<li>').text(data.username + ': ' + data.message));
});
}
The code socket.broadcast.emit means sending to all clients except sender.
Check out the Socket.IO cheatsheet.
When the client connects to the server a message is supposed to be emitted to the console. I'm not getting any errors so I'm confused as to what my problem actually is.
Server: As you can see the client connects.
Client: The message doesn't appear in the console.
(Forgive me for the links, I don't have 10 reputation)
How do I get the message to print to the console?
I've read other posts like this one, but they weren't helpful :(
When you do io.connect(), that call is asynchronous and not immediate. You cannot immediately emit to the server until the client generates the connect event:
var socket = io.connect()
socket.on('connect', function() {
// it is safe to call `.emit()` here
socket.emit("sndMsg", someData);
});
index.html
<html>
<head>
<script src='/socket.io/socket.io.js'></script>
<script>
var socket = io();
socket.on('welcome', function(data) {
addMessage(data.message);
// Respond with a message including this clients' id sent from the server
socket.emit('i am client', {data: 'foo!', id: data.id});
});
socket.on('time', function(data) {
addMessage(data.time);
});
socket.on('error', console.error.bind(console));
socket.on('message', console.log.bind(console));
function addMessage(message) {
var text = document.createTextNode(message),
el = document.createElement('li'),
messages = document.getElementById('messages');
el.appendChild(text);
messages.appendChild(el);
}
</script>
</head>
<body>
<ul id='messages'></ul>
</body>
</html>
server.js
var http = require('http'),
fs = require('fs'),
// NEVER use a Sync function except at start-up!
index = fs.readFileSync(__dirname + '/index.html');
// Send index.html to all requests
var app = http.createServer(function(req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(index);
});
// Socket.io server listens to our app
var io = require('socket.io').listen(app);
// Send current time to all connected clients
function sendTime() {
io.emit('time', { time: new Date().toJSON() });
}
// Send current time every 10 secs
setInterval(sendTime, 10000);
// Emit welcome message on connection
io.on('connection', function(socket) {
// Use socket to communicate with this particular client only, sending it it's own id
socket.emit('welcome', { message: 'Welcome!', id: socket.id });
socket.on('i am client', console.log);
});
app.listen(3000);
I have a small express application this also contains the socket program. When ever user success login it creates the session and socket connection perfectly.
But MY problem was when the express session expire or session delete by cookie manager, the socket still in the active connection. it receiving the messages. how to disconnect even if the session are not available after the success login.
Here my code was:
This is my html file which gets the alert message:
<!DOCTYPE html>
<html>
<head>
<script src="jquery.min.js"></script>
<script src="socket.io.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.ajax({
type: 'GET',
contentType: 'application/json',
url: './alert'
});
});
</script>
<script>
var socket = io.connect();
socket.on('message',function(data){
alert(data.msg);
});
</script>
</head>
<body>
<button>alert</button>
</bodY>
</html>
This is my socket and express code:
var express=require('express');
var app=express();
var session = require('express-session');
var server=require('http').createServer(app);
app.use(session({secret: 'abcd',resave:'false', saveUninitialized:'false',name:'usess',cookie: { maxAge: 10000 }));
var io=require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
socket.join('alerts');
socket.on('disconnect',function(data){
socket.leave('alerts');
console.log('leaved');
});
});
app.get('/login', function(req, res){
//here my authentication code//
req.session.login='logedin';
req.session.save();
res.sendfile('./template.html');
});
app.get('/', auth,function(req, res){
//index file contins the two text boxes for user name and pass//
res.sendfile('./index.html');
});
app.get('/alert',function(req,res){
io.sockets.in('alerts').emit('message',{msg:'hai'});
res.end();
});
server.listen(3000);
Thank You.
Maybe you can check if the req.session exists before emitting the message ?
app.get('/alert',function(req,res){
if(req.session)
io.sockets.in('sairam').emit('message',{msg:'hai'});
else
//Disconnect the client from server side
res.end();
});
For disconnecting the socket from server side check this answer;
https://stackoverflow.com/a/5560187/3928819
My server wants to send to the clients a message on connection. Then the client sends a message to the server .
My code is working fine when the client sends message to the server but the initial message that the server should send on connection is not received by the client.
This is my little code :)
server
var app = require('http').createServer(handler),
io = require('socket.io').listen(app, { log: false }),
fs = require('fs');
app.listen(8001);
function handler(req, res) {
fs.readFile(__dirname + '/client1.html', function(err, data) {
if (err) {
console.log(err);
res.writeHead(500);
return res.end('Error loading client1.html');
}
res.writeHead(200);
res.end(data);
});
}
io.sockets.on('connection', function (socket) {
console.log("running time");
socket.emit("serverMessage","server says hi");
socket.on('clientMessage', function () {
console.log("client message recieved");
});
});
client
<html>
<head>
<script src="/socket.io/socket.io.js"></script>
<script>
socket = io.connect("http://localhost:8001");
socket.on('connection', function(socket) {
socket.on("serverMessage", function(d) {
console.log("server send a message ");
});
});
function send() {
socket.emit('clientMessage', "Test Message From Client");
}
</script>
</head>
<body>
<button onclick="send()" >send</button>
</body>
Please any help?
There is a simple error in your client code. There is no event named connection for client. Instead the name is connect. Do this in client:
<script>
socket = io.connect("http://localhost:8001");
</script>
<script>
socket.on('connect', function(socket) {
socket.on("serverMessage", function(d) {
// you can alert something here like alert(d)
console.log("server send a message ");
});
});
</script>