i'm making a chat application divided by several namespaces, in other words i want to divide interests, some of them like to talk 'dogs' other wants to talk about 'cats' and so on...
This is my first version, in which i stored each namespace in a variable(it works perfectly) :
Server side:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/default', function(req, res){
res.sendfile('index1.html');
});
app.get('/dog', function(req, res){
res.sendfile('index2.html');
});
app.get('/', function(req, res){
res.sendfile('index.html');
});
var cns1 = io.of('/default');
//default nsp
cns1.on('connection', function(socket){
socket.on('chat message', function(msg){
cns1.emit('chat message', msg);
});
});
var cns2 = io.of('/dog');
//dog nsp
cns2.on('connection', function(socket){
socket.on('chat message', function(msg){
cns2.emit('chat message', msg);
});
});
var cnsindex = io.of('/');
//index nsp
cnsindex.on('connection', function(socket){
socket.on('chat message', function(msg){
cnsindex.emit('chat message', msg);
});
});
http.listen(3000,function(){
console.log('listening on *:3000');
});
index*.html
<script>
//on index.html
var socket = io.connect('http://localhost:3000/');
//on index2.html
//var socket = io.connect('http://localhost:3000/dog');
//on index1.html
//var socket = io.connect('http://localhost:3000/default');
$(function(){
$('#bb').click(function (){
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
});
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
});
</script>
Each namespaces keeps their messages private.
Now, when i wanted to store all Workspaces in an array to avoid repeating events, like that:
var app = require('express')();
var http = require('http').createServer(app);
var io = require('socket.io')(http);
app.get('/default', function(req, res){
res.sendfile('index1.html');
});
app.get('/dog', function(req, res){
res.sendfile('index2.html');
});
app.get('/', function(req, res){
res.sendfile('index.html');
});
var nss = [
io.of('/default'),
io.of('/dog'),
io.of('/')
];
for (i in nss)
{
nss[i].on('connection', function(socket){
socket.on('chat message', function(msg){
nss[i].emit('chat message', msg);
});
});
}
http.listen(3000,function(){
console.log('listening on *:3000');
});
In the second version doesn't receive messages for /dog and /default urls, and it allow sending messages from /dog and /default to /.
I'm stuck here, helps please!
Solved, this is a problem of closure thx to #levi :
for (i in namespaces)
{
namespaces[i].on('connection',handleConnection(namespaces[i]));
function handleConnection(ns)
{
return function (socket){
socket.on('chat message', function(msg){
ns.emit('chat message', msg);
});
}
}
}
Now my code works :)
Related
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
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 want to connect my socket server through flutter mobile application, but it's not working.
My server code (Node.js):
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = process.env.PORT || 3000;
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("biri geldşi")
socket.on('chat message', function(msg){
console.log(msg)
io.emit('chat message', msg);
});
});
http.listen(port, function(){
console.log('listening on *:' + port);
});
My Flutter application code:
import 'package:socket_io_client/socket_io_client.dart' as IO;
main() {
IO.Socket socket = IO.io('http://192.168.1.102:3000');
socket.on('connection', (_) {
print('connect');
socket.emit('chat message', 'test');
});
socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
}
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>