My code isn't logging any messages in my console, I need the code to log a message when I run my server
Server side
const path = require('path');
const http = require("http");
const express = require("express");
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
//set static folder
app.use(express.static(path.join(__dirname, 'public')));
//Run when client connects
io.on('connection', function(socket){
//welcome current user
socket.emit("message", 'Welcome to ChatApp');
//Broadcast when a user connects
socket.broadcast.emit('message', 'A user has join the chat');
//Runs when client disconnect
socket.on('disconnect', ()=>{
io.emit('message', 'A user has left the chat')
})
});
const PORT = 3000 || process.env.PORT;
server.listen(PORT, () => console.log('Server running on port ${PORT}'));
Client side
const socket = io();
io.sockets.on("message", message =>{
console.log("message")
})
its like as if the client side isnt functioning
The problem is in your client code.
You set up a variable named socket but then attempt to set a handler on io.sockets
Change:
const socket = io();
io.sockets.on("message", message =>{
console.log("message")
})
To:
const socket = io();
socket.on("message", message =>{
console.log("message")
})
Initiate the socket by providing required parameters like URL and the optional parameters if required
socket = io('<SERVER_URL_HERE>', {
reconnection: true, // optional
reconnectionDelay: 1000, // optional
reconnectionDelayMax : 25000, // optional
reconnectionAttempts: Infinity, // optional
autoConnect: true, // optional
query:{isAgent,agentId,isCustomer,projectId} // optional
})
Related
Need your help/guidance/suggestion for our scenario.
Issue: I am having some trouble connecting socket io client to socket io server. The error I got after running this code is connection time out.
My server code is :
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.Server(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ",port);
});
My client code is:
<script src = "socket.io.min.js"> </script>
<script>
var socket = io.connect(`wss://${document.location.hostname}:${port}`);
console.log(socket);
socket.on('done', (data) => {
console.log(data);
});
</script>
Your server code does not start in my node installation.
I correct your server code with this below and seems to work
fine on my node installation. You forgot to link express library
const port = process.env.PORT || 4004;
const http = require('http');
const socket = require('socket.io');
const express = require('express');
const app = express();
const httpServer = http.createServer(app);
const io = new socket.listen(httpServer);
io.on('connection', (socket) => {
console.log("Socket connected");
});
httpServer.listen(port, () => {
console.log("Listening on port ", port);
});
You can do with this script. This is my personal working script for socket IO chat app.
Backend Server
require("dotenv").config();
const port = process.env.SOCKET_PORT || 3000;
const main_server_url = process.env.SERVER_URL;
var express = require("express");
var app = express();
var server = app.listen(port);
var connectionOptions = {
"force new connection": true,
"reconnection": true,
"reconnectionDelay": 2000, //starts with 2 secs delay, then 4, 6, 8, until 60 where it stays forever until it reconnects
"reconnectionDelayMax": 60000, //1 minute maximum delay between connections
"reconnectionAttempts": "Infinity", //to prevent dead clients, having the user to having to manually reconnect after a server restart.
"timeout": 10000, //before connect_error and connect_timeout are emitted.
"transports": ["websocket"] //forces the transport to be only websocket. Server needs to be setup as well/
}
var io = require("socket.io").listen(server, connectionOptions);
var axios = require("axios");
var users = [];
var connections = [];
console.log("Server connected done");
io.sockets.on("connection", function (socket) {
var server_url = main_server_url;
console.log(server_url);
console.log(people);
connections.push(socket);
console.log("Connected : total connections are " + connections.length);
// rest of events of socket
});
Front End JS for load IO for client
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.js"></script>
<script type="text/javascript">
var base_url = YOUR_BASE_URL;
var port = YOUR_SOCKET_PORT;
var socket_port_url = base_url + ":" + port;
var socket = io(socket_port_url);
socket.on('done', (data) => {
console.log(data);
});
</script>
So basically what i am trying to do is build a chat app with a login system but for some reason i cant put it together and i am getting an error when i join to the room the chat.hbs can't find the socket.io.js file and also the main.js is getting a reference error with the const socket = io(); (the chat app works fine without the login system)
Failed to load resource: the server responded with a status of 404 (Not Found)
Uncaught ReferenceError: io is not definedat main.js:11
This is the app.js file
const express = require("express");
const path = require('path');
const http = require('http');
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const botName = "Bot";
app.use(express.static(path.join(__dirname, 'public')));
app.use(express.urlencoded({ extended: false }));
// Parse JSON bodies (as sent by API clients)
app.use(express.json());
app.use(cookieParser());
app.set('view engine', 'hbs');
//eldönti az útvonalat
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
This is the main.js
const chatForm = document.getElementById('chat-form');
const chatMessages = document.querySelector('.chat-messages');
const roomName = document.getElementById('room-name');
const userList = document.getElementById('users');
// Felhasználó név és szoba név URL-ből
const { username, room } = Qs.parse(location.search, {
ignoreQueryPrefix: true,
});
const socket = io();
// Csatlakozik chat szobába
socket.emit('joinRoom', { username, room });
// Lekérdezi a szobát felhasználókat
socket.on('roomUsers', ({ room, users }) => {
outputRoomName(room);
outputUsers(users);
});
And the chat.hbs
<script src="/socket.io/socket.io.js"></script>
<script src="/main.js"></script>
Well the problem was that I used:
app.listen(5001, () => {
console.log("Server started on Port 5001");
})
instead of:
server.listen(5001, () => {
console.log("Server started on Port 5001");
})
Szia, you will need to wait for the DOM to load.
window.addEventListener('load', function () {
// Your code goes here
const socket = io();
socket.on("connect", () => {
// you can only emit once the connection is established.
socket.emit('joinRoom', { username, room });
});
})
I am using socket io and express. i want to broadcast my message to all users of room but insted of users of that room all users who are connected recive message. Room id is room id
const app = require('express')();
const http = require('http').Server(app);
const io = require('socket.io')(http);
const port = process.env.PORT || 8080;
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
app.use(cors({origin: true}));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
io.on('connection', async (socket) => {
console.log('user connected');
}
Now This is message block
socket.on('message' , async (data)=>{
//want to broadcast message to all users except sender
//Room is Group1Room and room id is RoomId
io.emit('message', {message:"hello" , socketId:socket.id})
//recive message
io.on('message' , (data)=>{
console.log('data is ' data);
})
}
```ata,{ where: { id } });
socket.emit is used to emit an event globally.All user connected to socket will will listen and get data. for sharing a message in room use
socket.broadcast.to(roomid).emit()
your code will be like that
socket.broadcast.to(event).emit( 'message' , {message:message,
socketId:socket.id
});
I have these code for a Chat App and it is only working in Local Server
I have already tried the following. Calling io() without any path arguments.
// Client Side Code
socket = io();
socket.connect({ query: `username=${props.username}` })
The above didnt work. The app runs but does not show other user's messages.
// Client Side Code
socket = io('http://myherokuapp:3001', { query:
`username=${props.username}` }).connect();
Neither did the above code work. The app crashed on this one.
Here is my actual source code:
// Server Side Code
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || 3001;
const app = express();
const http = require("http");
const cors = require("cors");
const io = require("socket.io");
const server = http.createServer(app);
const socketIo = io(server);
app.use(cors());
app.get('/messages', (req, res) => {
res.sendFile(path.resolve('./public/index.html'));
});
socketIo.on('connection', socket => {
const username = socket.handshake.query.username;
console.log(`${username} connected`);
socket.on('client:message', data => {
console.log(`${data.username}: ${data.message}`);
socket.broadcast.emit('server:message', data);
});
socket.on('disconnect', () => {
console.log(`${username} disconnected`);
});
});
server.listen(PORT, () => {
console.log(`🌎 ==> API server now on port ${PORT}!`);
});
// Client Side Code
socket = io('http://localhost:3001', { query:
`username=${props.username}` }).connect();
socket.on('server:message', message => {
addMessage(message);
});
socket.emit('client:message', messageObject);
addMessage(messageObject);
I expect the chat app to be working same as it does in localhost.
I was following the second example here:
https://github.com/socketio/socket.io-client
and trying to connect to a website that uses websockets, using socket.io-client.js in node.
My code is as follows:
var socket = require('socket.io-client')('ws://ws.website.com/socket.io/?EIO=3&transport=websocket');
socket.on('connect', function() {
console.log("Successfully connected!");
});
Unfortunately, nothing gets logged.
I also tried:
var socket = require('socket.io-client')('http://website.com/');
socket.on('connect', function() {
console.log("Successfully connected!");
});
but nothing.
Please tell me what I'm doing wrong. Thank you!
Although the code posted above should work another way to connect to a socket.io server is to call the connect() method on the client.
Socket.io Client
const io = require('socket.io-client');
const socket = io.connect('http://website.com');
socket.on('connect', () => {
console.log('Successfully connected!');
});
Socket.io Server w/ Express
const express = require('express');
const app = express();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const port = process.env.PORT || 1337;
server.listen(port, () => {
console.log(`Listening on ${port}`);
});
io.on('connection', (socket) => {
// add handlers for socket events
});
Edit
Added Socket.io server code example.