I have a hard time understanding when server "send" the data and when client "get" the data and vice versa.
The code is in their example
in index.js for nodejs
// server side
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log('a user connected');
// create chat message
socket.on('chat message', function(msg){
io.emit('chat message', msg);
console.log('message: ' + msg);
});
socket.on('disconnect', function(){
console.log('user disconnected');
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
and in the script
$( function(){
'use strict';
// client side
console.log("starting chat...");
var socket = io();
$('form').submit(function(){
// call event chat message
socket.emit('chat message', $('#m').val());
$('#m').val('');
return false;
});
// create chat message event on client
socket.on('chat message', function(msg){
$('#messages').append($('<li>').text(msg));
})
});
as you can see on index.js it create a chat message and using io it emmit it. The same thing is on in the script. So the question is how does the server and client "talk" with each other? and what it is the different between emmit and on ?
Whenever we are using socket io , we use emit to send server a message with given message identifier and server now replies client by emitting a message with some message identifier say x, then we use that on method and pass x identifier and grab the message from server.
Related
I'm creating a socket.io server like so:
var http = require('http');
var io = require('socket.io');
var port = 8080;
var server = http.createServer(function(req, res){
res.writeHead(200,{ 'Content-Type': 'text/html' });
res.end('<h1>Hello Socket Lover!</h1>');
});
server.listen(port);
// Create a Socket.IO instance, passing it our server
var socket = io.listen(server);
// Add a connect listener
socket.on('connection', function(client){
console.log('Connection to client established');
// Success! Now listen to messages to be received
client.on('message',function(event){
console.log('Received message from client!',event);
});
client.on('disconnect',function(){
clearInterval(interval);
console.log('Server has disconnected');
});
});
console.log('Server running at http://127.0.0.1:' + port + '/');
The server works fine and starts, however when I'm connecting through js like this:
$(function(){
var socket = io();
socket.connect('http://localhost:8080');
});
It's not connecting and I'm getting this in dev tools console.
polling-xhr.js:264 GET http://file/socket.io/?EIO=3&transport=polling&t=Lz53lhL net::ERR_NAME_NOT_RESOLVED
I'm loading socket.io.js like this:
<script src="http://127.0.0.1:8080/socket.io/socket.io.js"></script>
Change
$(function(){
var socket = io();
socket.connect('http://localhost:8080');
});
to
$(function(){
var socket = io('http://localhost:8080');
});
You need to pass the url of your socket server to the io function
I'm trying to build a simple app using Node, Express (^4.15.3), and socket.io (^2.0.3). I'm building a simple chat app, however each time I add a new message, I get an additional response each time.
For example, if the first message was "Hello", I would be returned:
Hello
If I then add a subsequent message of "Is anyone there?", I get back:
Is anyone there?
Is anyone there?
And so on...each time I get an additional response back.
Here's my code - it feels like it's something really obvious and I may have been staring at it too long...
//app.js
var express = require("express");
var bodyParser = require("body-parser");
var expressValidator = require('express-validator');
var session = require('express-session');
var passport = require("passport");
var app = express();
var http = require('http');
var server = http.createServer(app);
var io = require('socket.io').listen(server);
app.use(express.static("public"));
app.set("view engine", "ejs");
server.listen(process.env.PORT || 3000, process.env.IP, function(){
console.log("Server starting...");
});
app.get('/testsocket', function(req, res){
res.render('sockets/test');
});
io.sockets.on('connection', function(socket){
console.log('Connected')
socket.on('send message', function(data){
console.log('Got the message...');
io.sockets.emit('new message', data)
});
});
And then client side
//client side
$(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>");
});
});
});
I think the problem is that you're registering the listener for new message inside your submit function. So each time you submit the form you register a new listener, in addition to any previous listeners. Try putting the socket.on('new message', ... section outside the submit handler.
This question already has answers here:
What is the best practice for serving html in node.js with express.js?
(2 answers)
Closed 5 years ago.
I'd like to implement a chatroom by node.js.
I use the template provided by socket.io.
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs');
app.get('/', function(req, res) {
fs.readFile(__dirname + '/style.css'); // I don't know how to import the style.css to the chat.html
// fs.readFile(__dirname + '/images/'); // And how to add images file to the server
res.sendFile(__dirname + '/chat.html');
});
io.on('connection', function(socket) {
console.log('a user connected');
socket.on('disconnect', function() {
console.log('user disconnected');
});
socket.on('chat message', function(msg) {
console.log('message: ' + msg);
})
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
socket.broadcast.emit('hi');
});
http.listen(8888, function() {
console.log('listening on *:8888');
});
When I type
node index.js
in the terminal, it'll show up
listening on *:8888
(node:12873) [DEP0013] DeprecationWarning: Calling an asynchronous function without callback is deprecated.
Now, the server can work but the format is gone.
I don't know how to correct this. I hope that the chat.html can be in the format specified by the style.css and the messages can be sent in the format(also specified by the style.css) I desired not just pure text.
You have to tell node the directory that you plan to use for "Static files".
You do it like so
const staticCont = express.static(__dirname + "/public");
Where "public" is the name of the folder that will hold your static content like CSS or front end JS files etc.
hope this helps
Im using the following code in index.js
io.on('connection', function(socket){
console.log('a user connected');
console.log(socket.id);
});
the above code lets me print the socket.id in console.
But when i try to print the socket.id on client side using the following code
<script>
var socket = io();
var id = socket.io.engine.id;
document.write(id);
</script>
it gives 'null' as output in the browser.
You should wait for the event connect before accessing the id field:
With this parameter, you will access the sessionID
socket.id
Edit with:
Client-side:
var socketConnection = io.connect();
socketConnection.on('connect', function() {
const sessionID = socketConnection.socket.sessionid; //
...
});
Server-side:
io.sockets.on('connect', function(socket) {
const sessionID = socket.id;
...
});
For Socket 2.0.4 users
Client Side
let socket = io.connect('http://localhost:<portNumber>');
console.log(socket.id); // undefined
socket.on('connect', () => {
console.log(socket.id); // an alphanumeric id...
});
Server Side
const io = require('socket.io')().listen(portNumber);
io.on('connection', function(socket){
console.log(socket.id); // same respective alphanumeric id...
}
The following code gives socket.id on client side.
<script>
var socket = io();
socket.on('connect', function(){
var id = socket.io.engine.id;
alert(id);
})
</script>
To get client side socket id for Latest socket.io 2.0 use the code below
let socket = io();
//on connect Event
socket.on('connect', () => {
//get the id from socket
console.log(socket.id);
});
How do I make a server that has a socket connecting to one client(Client A) also have a socket to another server? Basically how do I have the server become a client as well(to another server)?
If the answer is to load the socket.io-client then how would I do that in a javascript file?
var app = require('express')();
var http = require('http').Server(app);
var http2 = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
io.on('connection', function(socket){
console.log("asdf");
socket.on('chat message', function(msg){
io.emit('chat message', msg);
});
});
http.listen(3050, function(){
console.log('listening on *:3050');
});
http2.listen(1337, function(){
console.log('listening on *:1330');
});
var socket = require('socket.io-client')('http://localhost:1337');
socket.on('connect', function(){
console.log('connected');
});
I assume you mean that you want to run a node server as a client since you mention javascript file. Here is how to set up a socket client in node. Get the package npm i socket.io-client. Then use it in node as shown below.
var socket = require('socket.io-client')('http://localhost:1337');
socket.on('connect', function(){
console.log('connected')
});