Do I need socket.io-client on browser-side of things? - node.js

EDIT: The answer appears to be no.
I'm new to Node.js, bower and Socket.IO and I'm not sure what I need for my purpose.
I'm making an app that has a frontend (where browsers connect) and a backend (a single Node.js server).
What do I need to create a Socket.IO server instance on the backend? What do I need on the client-side? Does the Socket.IO package contain both?

First install socket.io using below command
npm install socket.io
and the call socket.io in your server js File
var io = require('socket.io');
And the create connection in your server js file
var app = express();
app.get('/', function(req, res){
fs.readFile('index.html', function(Error,data){
res.writeHead(200,{'Content-Type':'text/html'});
res.write(data);
res.end();
});
});
server = http.createServer(app);
var IO = io.listen(server);
server.listen(3000);
IO.sockets.on('connection', function(socket) {
socket.on('msg_to_server', function(data) {
console.log(data);
});
});
Add this script inside head Tag in your index.html
<script src="/socket.io/socket.io.js"></script>
in your index.html create socketio connection
var socketio = io.connect("127.0.0.1:3000");
send some data to server following way
socketio.emit('msg_to_server',{ message : 'some data' });

Related

Why do I need to add "require("http")" when I already have express?

I am trying to follow this tutorial on creating a simple chat application using socket.io. I am at the part of the tutorial where I have to insert all of the code below into a js file and initiate it. I just don't understand why the 2nd of code exist, I heard that express can do a lot more than http. Instead of using the "http.listen" code, can't "app.listen" be used and "app" passed to "io" instead?
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');
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
Why do I need to add “require(”http“)” when I already have express?
You don't have to manually load the http module yourself. You use express to create an http server for you (it will load the http module for you) and integrate it with socket.io without manually loading the htttp module like this:
const app = require('express')();
app.get('/', function(req, res){
res.sendFile(__dirname + '/index.html');
});
const server = app.listen(3000, function(){
console.log('listening on *:3000');
});
const io = require('socket.io')(server);
io.on('connection', function(socket){
console.log('a user connected');
});
Internally, app.listen() loads the http module for you, creates a server and then starts it, returning the server object which you can then use with socket.io.
Inside of express, this is the code for app.listen():
const http = require('http');
app.listen = function listen() {
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
So, somebody had to load the http module. If you use app.listen(), the express will do it for you.
You are right. Express is a framework that sits on top of the nodejs application and provides a much easier,provided more middleware to handle routes, session and cookies and more efficient way to create server as such
var express = require('express');
var app = express();
app.listen(3000);
In this example, for the purpose of creating a socket between different channels, you have to use HTTP to indicate that the socket is used to handle HTTP requests/responses. You simply can't pass an entire express application to io.

socket.io error on client side

I spend a few days on the problem.I am trying to build a page with socket.io.
I am a beginer of node.js & socket.io. I read the socket.io doc, and build the page step by step.
And then i got a error, Uncaught ReferenceError: io is not defined
But i can get the js content from http://localhost:3000/socket.io/socket.io.js
I use var socket = io.connect('http://localhost') or use var socket = io() on client side. Neither is ok.What show i do?
Here is my code in server side:
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var port = 3000;
http.listen(port, function(){
console.log('Server listening at port %d', port);
})
In client side:
var socket = io();
socket.on('news', function(data){
console.log(data);
})
On the client side, you should use the server.io client
import io from 'socket.io-client';
You can run
npm i socket.io-client
to install the dependency or alternatively you can serve the file socket.io.js found in the dist folder provided from https://www.npmjs.com/package/socket.io-client
<script src="/socket.io/socket.io.js"></script>
Not tested
In your pug template, you can do in head or body,
doctype html
html(lang="en")
head
script(src="/socket.io/socket.io.js").
//Your logic here

Fail to use socket.io not found

My structure
game.js
node_modules\
public\
|index.html
|js\main.js
game.js is nodejs server and in plubic folder is client side
In index.html I have
<script src="/socket.io/socket.io.js"></script>
But when i run in web browser it say
GET http://localhost:1000/socket.io/socket.io.js 404
(index):3 Uncaught ReferenceError: io is not defined
at (index):3
But when i download socket.io.js and make like this
game.js
node_modules\
public\
|index.html
|js\main.js
|socket.io\socket.io.js
And run again it localhost:1000 say
localhost:1000/socket.io/?EIO=3&transport=polling&t=Lg5U91n 404 (Not Found)
what is mistake. I run in window. How to fix that thank.
You will need to include socketio-client on the client side via the script tag. That will allow IO to be defined.
<script>
var socket = io.connect('http://localhost:1000');
socket.on('connect', function(data) {
//Do Something here
});
</script>
You will also need to make sure on your backed (the server that socketio is connecting to) has socketio properly defined and is being used in the HTTP server. An example would be:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res,next) {
res.sendFile(__dirname + '/index.html');
});
server.listen(1000);
io.on('connection', function(client) {
console.log('Client connected...');
//socket code here
});
Its very hard for us to help you without any code sample of what you are working with. The example provided is a very BASIC way of getting socketio up and running.
Checkout the socketio client github that has a quick and simple demonstration of what to do as well:
Socket.io Client Github

expressJS and socket.io listening to different ports and socket.io client connect

So I have a nodejs application which uses socket.io and expressjs
I use port '3000' for the express app and port '8080' for the socket app
Is it possible to use the same port for both these services?(express and socket.io)
When i want to connect to a socket from the client, I use the following code:
var socket = io('http://localhost:8080')
whats the right way of connecting to it( I see various ways in tutorials across the internet) and have no clue.
Is it possible to use the same port for both these services?(express and socket.io)
yes
var app = require('express')();
var server = require('http').createServer(app);
var io = require('socket.io')(server);
server.listen(8080); //or 3000
When i want to connect to a socket from the client, I use the following code:
At the front end :
include socket.io lib
<script src="/socket.io/socket.io.js"></script>
<script>
var socket = io.connect('http://localhost:8080'); //or 3000
</script>
EDIT :
without express
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(8080);
For more info socket.io
Yes, it is possible for both to use the same port. In fact, you should use the same port to make the client connect to your web socket when he sends a request. Socket.io docs has tutorial on how to connect with express.
Code from socket.io docs:
var app = require('express').createServer();
var io = require('socket.io')(app);
app.listen(80);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
io.on('connection', function (socket) {
socket.emit('news', { hello: 'world' });
socket.on('my other event', function (data) {
console.log(data);
});
});
If you want to connect socket with express-generator generated template, you this:
stackoverflow post

cannot get client server running using express in node.js

hey i just started tinkering with node.js and am a complete noob. i am trying to get a simple client server communication going using socket.io and express (i have never used these before).
here is my code for the app(app.js):
var sys = require('sys'),
express = require('express'),
app = express('localhost');
http = require('http'),
server = http.createServer(app),
io = require('socket.io').listen(server);
app.use(express.static(__dirname + '/public'));
app.get('/', function (req, res) {
res.send('Hello World');
});
app.listen(3000);
var socket = require('socket.io').listen(server);
socket.on('connection', function (client){
// new client is here!
setTimeout(function () {
client.send('Waited two seconds!');
}, 2000);
client.on('message', function () {
}) ;
client.on('disconnect', function () {
});
});
and here is my code for the client(client.html):
<html>
<p id="text">socket.io</p>
<script src="/socket.io/socket.io.js"></script>
<script>
$(document).ready(function(){
var socket = new io.Socket(),
text = $('#text');
socket.connect();
socket.on('connect', function () {
text.html('connected');
});
socket.on('message', function (msg) {
text.html(msg);
});
socket.on('disconnect', function () {
text.html('disconnected');
});
});
</script>
i got most of the code from:
NodeJS + socket.io: simple Client/Server example not working
and the changed it to be compatible with express 3.x
however when i run the server and open my client using chrome it tells me that it is unable
to load resource file:///socket.io/socket.io.js
i have already installed express and socket.io using npm
also i have read through atleast 20 similar posts and have not been able to find an answer
please help me. thank you
socket.io.js file needs to be served from port 3000, like localhost:3000.
So here is what you do change
<script src="/socket.io/socket.io.js"></script> to
<script src="http://localhost:3000/socket.io/socket.io.js"></script>
Are you opening the client.html page directly from the local file system? The request for socket.io.js should look like http://localhost/socket.io/socket.io.js not file:///socket.io/socket.io.js.

Resources