Hi I am making a chat site with the url http://localhost/Seminarska%20naloga%20NRSA/index.php?stran=chat
Once the message is submitted the server doesn't recive it and the client doesn't even connect to the server. The server is running on http://localhost:3000 when the code is in index.html file the chat works fina and with no problems connects to the server but when i put it in the php file called chat.html.php the connection fails.
HTML code:
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/Seminarska naloga NRSA/template/node_modules/socket.io/client-dist/socket.io.js"></script>
<script>
const socket = io("http://192.168.88.152:3000");
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
Server code:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname+'/chat.html.php');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
In the console there are no errors or warnings if the code is in index.html and i go to http://logalhost:3000 the ctah works perfectly.
This should be your client
<script src="/Seminarska naloga NRSA/template/node_modules/socket.io/client-dist/socket.io.js"></script>
<script>
const socket = io("http://192.168.88.152:3000");
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('SendMsg', input.value);
input.value = '';
}
});
socket.on('RecieveMsg', msg => {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
This should be your server
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const io = require("socket.io")(server,
cors: {
origin: 'http://localhost',
methods: ["GET", "POST"]
}
);
app.get('/', (req, res) => {
res.sendFile(__dirname+'/chat.html.php');
});
io.on('connection', (socket) => {
console.log('a user connected');
io.on('SendMsg', msg => {
console.log('Message: ' + msg);
io.emit('RecieveMsg', msg);
});
io.on('disconnect', () => {
console.log('A user disconnected');
})
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
all of your io.on() functions should be inside of io.on('connection'), because you want your server to listen after the connection.
Hope this helps :D
Related
I am trying to make a simple chat room with Socket.IO, but for some reason I keep on getting "Cross-Origin Request Blocked" errors.
Errors on the chat page
Currently I am using the code from https://socket.io/get-started/chat/
Server code:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html.php');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('listening on *:3030');
});
HTML code:
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="/chat-exmple/node_modules/socket.io/client-dist/socket.io.js"></script>
<script>
const socket = io("http://localhost:3030");
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
I tried to change the port numbers in the URL and rewriting the code, but I still don’t know what to do to fix this problem.
Do you have already try this?
const io = require('socket.io'
(server, {
cors: {
origin: '*',
}
});
Hi I am quite new to socket io, and I am trying to make a simple chat. The problem is that I keep on getting errors for failed loading. I can't figure it out what is wrong with my code. I am using the code from: https://socket.io/get-started/chat/
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off" /><button>Send</button>
</form>
<script src="https://cdn.socket.io/3.0.0/socket.io.js"><script/></script>
<script>
var socket = io("http://192.168.88.152:3000");
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
</script>
The code for backent:
const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);
app.get('/', (req, res) => {
res.sendFile(__dirname + '/chat.html.php');
});
io.on('connection', (socket) => {
console.log('a user connected');
});
io.on('connection', (socket) => {
console.log('a user connected');
socket.on('disconnect', () => {
console.log('user disconnected');
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
console.log('message: ' + msg);
});
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('chat message', msg);
});
});
server.listen(3000, () => {
console.log('listening on *:3000');
});
In this link It hasn't serve static file in socket.io example. So you can fix this error by using script as cdn:
<script src="https://cdn.socket.io/3.0.0/socket.io.js"><script/>
or download cdn file and serve it your file with express: link
I have 2 pages: play page, live page and server. I want to use socket.io to do this: i want to send data from play page to server and then to live and show a text that update automatically when I change it in play page.
play page emit this
var n = <%-JSON.stringify(v1)%>;
var socket = io.connect('http://localhost:3000');
socket.emit('event', { message: n });
server code
var server = app.listen(3000); //port 3000 is only for sockets. my app has web traffic on port 5000.
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('event', function(data) {
console.log('A client sent us this dumb message:', data.message);
var n = data.message;
console.log("");
console.log("data received from play client..trying to send to live");
console.log("");
console.log("var n is");
console.log(n);
console.log("sending data...");
socket.emit('event', { message: n });
Whatever I do in live page it don't receive message.
I solved 50% of my problem creating another socket in server.js that listen to port 3002 and this worked. But now my content don't update automatically on live page. I have to refresh manually and I don't want this.
This is my new server.js code that worked(without realtime update on live.ejs page):
const express = require('express');
const store = require('./store');
const storeLyric = require('./storeLyric');
const searchF = require('./search');
// middleware to handle HTTP POST request
// extract the entire body portion of an incoming request and exposes it on req.body
const bodyParser = require('body-parser');
const app = express();
app.set('port', (process.env.PORT || 5000));
app.set('view engine', 'ejs');
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
///new
var server = app.listen(3000);
var io = require('socket.io')(server);
var server2 = app.listen(3002);
var io2 = require('socket.io')(server2);
io.on('connection', function(socket) {
socket.on('event', function(data) {
console.log('A client sent us this dumb message:', data.message);
var n = data.message;
console.log("");
console.log("data received from play client..trying to send to live");
console.log("");
console.log("var n is");
console.log(n);
console.log("sending data...");
io2.on('connection', function(socket2) {
socket2.on('live', function(data2) {
console.log('status from live client:', data2);
socket2.emit('live', n);
});
});
////////////////////
});
});
//end new
////////////
// default page
app.get('/', (req,res) => {
let students = [];
var end = req.query.end;
if(end==1 || end==2){
io2.on('connection', function(socket2) {
socket2.on('live', function(data2) {
console.log('status from live client:', data2);
socket2.emit('live', '');
});
});
}
store.studentList().then((req,respond) => {
students = req;
res.render('pages/index', {
title: '',
students:students
})
})
})
//live page
app.get('/live', function (req, res) {
res.render('pages/live', {
n:'gsgs'
})
})
// search page
app.get('/search', (req,res) => {
let search = [];
var q = req.query.q; // $_GET["q"]
searchF.search(q).then((req,respond) => {
search = req;
res.render('pages/search', {
search:search,
q:q
})
})
})
// play page
app.get('/play', (req,res) => {
let lyrics = [];
var vers = req.query.vers; // $_GET["vers"]
var for_id = req.query.for_id; // $_GET["vers"]
storeLyric.lyrics(for_id, vers).then((req,respond) => {
lyrics = req;
res.render('pages/play', {
title: '',
lyrics:lyrics
})
});
////////
})
app.listen(app.get('port'), () => {
console.log("Listening to port: ", app.get("port"))
});
What I'm doing wrong and why socket.io doesn't work in realtime?
Thanks for help!
You need to emit the event from server side to the client side and then catch data there
var server = app.listen(3000);
var io = require('socket.io')(server);
io.on('connection', function(socket) {
socket.on('event', function(data) {
var n = data.message;
io.sockets.emit('event', message);
});
And then on frontend in live page you write this
var n = <%-JSON.stringify(v1)%>;
var socket = io.connect('http://localhost:3000');
socket.on('event', (data)=>{
console.log(data)
});
I am trying get the json data from url example.com and pass that to my index.html. How can I do that. It's not working. I want to update data every 5 second file index.html.
app.js
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var https = require('https');
app.get('/', function(req, res) {
res.sendfile('index.html');
//How to use req object ?
});
io.on('connection', function(socket) {
console.log('A user connected');
setInterval(function() {
urlString = "https://example.com/trip?trip_id=1234";
$.get(urlString, function(data, status){
console.log('data');
})
socket.send('');
}, 4000);
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
http.listen(3000, function() {
console.log('listening on *:3000');
});
index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(data){document.write(data)});
</script>
You were doing a number of things wrong:
$.get() doesn't run on the server. That's client-side jQuery code
You should create one setInterval() on your server, not a new one for each client connection
You can then just broadcast the results to all connected clients
If you document.write() in the client after the page is loaded, it just clears your original document so you want to append info to the DOM, not use document.write().
When you send data with socket.io, you send a message name and some data .emit(someMessage, someData).
Here's one way to do your code:
// server.js
const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const request = require('request');
app.get('/', function(req, res) {
res.sendfile('index.html');
});
// create one and only one interval
setInterval(function() {
let urlString = "https://example.com/trip?trip_id=1234";
request(urlString, function(err, response, data) {
if (err) {
console.log("error on request", err);
} else {
console.log('data');
// send to all connected clients
io.emit('message', data);
}
});
}, 5000);
io.on('connection', function(socket) {
console.log('A user connected');
socket.on('disconnect', function () {
console.log('A user disconnected');
});
});
server.listen(3000, function() {
console.log('listening on *:3000');
});
// index.html
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io();
socket.on('message', function(data){
let div = document.createElement("div");
div.innerHTML = data;
document.body.appendChild(div);
});
</script>
I'm working on basic chat-application running on express.js and socket.io.
Server-side code:
var express = require("express");
var app = express();
var server = require('http').createServer(app);
var io = require("socket.io").listen(server);
var path = require("path");
app.use(express.static(path.join(__dirname, "public")));
app.set("view engine", "ejs");
server.listen(process.env.PORT || 3000, function() {
console.log("Server listening");
})
app.get("/", function(req, res) {
res.render("chat");
})
io.sockets.addListener("connection", function(socket) {
socket.addListener("chat-message", function(message, nickname) {
io.sockets.emit("chat-message", message, nickname)
})
})
Client-side code:
var socket = io();
var nickname = prompt("Whats your name?");
var input = document.getElementById("text-input");
var container = document.getElementById("chat-container");
input.addEventListener("keydown", function() {
if (event.keyCode == 13) {
event.preventDefault();
if (input.value !== "") {
socket.emit("chat-message", nickname + ": " + input.value);
input.value = "";
}
}
})
socket.addEventListener("chat-message", function(message) {
container.innerHTML += message + "</br>";
})
Is there any way to avoid deleting info from the webpage after refresh?
You can save all the messages and nicknames in a globar variable and send them on every new connection to the socket.
var messages = [];
io.sockets.addListener("connection", function(socket) {
//send messages to new connection
socket.addListener("chat-message", function(message, nickname) {
messages.push({message: message, nickname: nickname});
io.sockets.emit("chat-message", message, nickname)
})
})
[Edit]
Client Side
socket.addEventListener("chat-previous-messages", function(messages) {
for(let i = 0; i < messages.length; i++){
container.innerHTML += messages[i].message + "</br>";
}
})
Server side
var messages = [];
io.sockets.addListener("connection", function(socket) {
socket.emit('chat-previous-messages', messages); //new code
socket.addListener("chat-message", function(message, nickname) {
messages.push({message: message, nickname: nickname});
io.sockets.emit("chat-message", message, nickname)
})
})
Or you can serve the chat page with the messages already displayed
app.get("/", function(req, res) {
res.render("chat", messages);
})
//in the html part something like this
#chat-container
- each message in messages
message.message + '<br>'