Connecting client to server using Socket.io - javascript

I'm relatively new to node.js and it's addons, so this is probably a beginnersquestion.
I'm trying to get a simple HTML page on a webserver connect to a different server running node.js with websocket.io.
My code looks like this:
Client
<script src="socket.io/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = new io.Socket();
socket.connect('http://127.0.0.1:8080');
// Add a connect listener
socket.on('connect',function() {
console.log('Client has connected to the server!');
});
// Add a connect listener
socket.on('message',function(data) {
console.log('Received a message from the server!',data);
});
// Add a disconnect listener
socket.on('disconnect',function() {
console.log('The client has disconnected!');
});
// Sends a message to the server via sockets
function sendMessageToServer(message) {
socket.send(message);
};
</script>
Serverside
// Require HTTP module (to start server) and Socket.IO
var http = require('http');
var io = require('socket.io');
var port = 8080;
// Start the server at port 8080
var server = http.createServer(function(req, res){
// Send HTML headers and message
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 + '/');
Starting up the server works fine and running http://localhost:8080 in my browser also works, returning 'Hello Socket Lover' as expected. But I want to make a different page talk to the sockets, not run one from node.js.
But when I run it, nothing happens and the Chrome console returns:
Failed to load resource http://undefined/socket.io/1/?t=1333119551736
Failed to load resource http://undefined/socket.io/1/?t=1333119551735
I've been at this all day. Any help?

Have you tried loading the socket.io script not from a relative URL?
You're using:
<script src="socket.io/socket.io.js"></script>
And:
socket.connect('http://127.0.0.1:8080');
You should try:
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
And:
socket.connect('http://localhost:8080');
Switch localhost:8080 with whatever fits your current setup.
Also, depending on your setup, you may have some issues communicating to the server when loading the client page from a different domain (same-origin policy). This can be overcome in different ways (outside of the scope of this answer, google/SO it).

You need to make sure that you add forward slash before your link to socket.io:
<script src="/socket.io/socket.io.js"></script>
Then in the view/controller just do:
var socket = io.connect()
That should solve your problem.

Instead of:
var socket = new io.Socket();
Try:
const socket = io();
Also add a server file:
const http = require('http');
const express = require('express');
const app = express();
const server = http.createServer(app);
app.use(express.static(__dirname + '/public'));
const io = require('socket.io')(server);
const PORT = 5000;
server.listen(PORT, () => {
console.log(`Server is Listening On Port ${PORT}`);
});

Related

How to use socket.io in localhost

I want to use socket.io in localhost which is my development environment:
client code:
const socket = io.connect('https://localhost:4000/');
socket.emit('trim-movie/go', data);
socket.on('trim-movie-response', trimResponse);
server :
const server = app.listen(port, () => console.log('server is online...'));
const io = socket(server);
io.on("connection", (socket) => {
socket.on('trim-movie/go', (data) => trimMovie(data, socket));
});
But I get this error:
socket.io.js?v=1:1415 GET
https://localhost:4000/socket.io/?EIO=4&transport=polling&t=OI2OmiX
404 (Not Found)
How to fix this?
Your client shows an https URL. Your server is starting an http server, NOT an https server because app.listen() only starts an http server. There's no way and https url will connect to an http server so these will ever match up.
Change the client to:
const socket = io.connect('http://localhost:4000/');
Or, if your page is already loaded from that same server, you can just use:
const socket = io();
and the client will get the domain and port from the URL of the containing web page.
Also make sure that the server-side port variable is set to 4000.

Connection to nodejs (express) refused

I’m a long term programmer, but haven’t used nodejs much in my code. Now I need to use it in my current code and I’ve ran into a problem that I can’t seem to figure out myself, I have googled a lot but nothing seem to fix it.
I am trying to get my website to connect to the nodejs server running on same host.
If I visit the url in my browser, it works fine (http://localhost:6857/socket.io/?EIO=4&transport=polling) and I see this respond
0{"sid":"s_v860SbNO4toknPAAAA","upgrades":["websocket"],"pingInterval":25000,"pingTimeout":20000}
But when I try to connect thru the website, I just get
GET http://localhost:6857/socket.io/?EIO=3&transport=polling&t=N_gL_HZ net::ERR_CONNECTION_REFUSED
Can someone guide my in the right direction for how to fix this, so I can begin using nodejs inside my website?
This is my server.js
// use express
var express = require("express");
// create instance of express
var app = express();
// use http with instance of express
var http = require("http").createServer(app);
// start the server
var port = 6857;
http.listen(port, '0.0.0.0', function () {
console.log("Listening to port " + port);
});
// create socket instance with http
var io = require("socket.io")(http);
// add listener for new connection
io.on("connection", function (socket) {
// this is socket for each user
console.log("User connected", socket.id);
});
io.on("connect_error", (err) => {
console.log(`connect_error due to ${err.message}`);
});
And this is my JS code inside my website
<script>
var server = "http://localhost:6857/";
var io = io(server);
</script>
Socket IO requires you to enable CORS explicitly - Thus why you get the error stated above.
To enable CORS, please see the following link

Node JS as HTTP Server and as tcp socket client at once

I'm creating node js application as a http server that communicate to tcp socket server, and the code look's like this:
var http = require('http');
var net = require('net');
var url = require('url') ;
const PORT=8080;
var client = new net.Socket();
client.connect(9000,'xxx.xxx.xxx.xxx', function(){
console.log('Connected');
});
function handleRequest(request, response){
var qo = url.parse(request.url,true).query;
if(typeof qo.q=="undefined"){
response.end("ERROR");
}else{
client.write(decodeURIComponent(qo.q));
client.on('data',function(data){
response.writeHead(200, {'Content-Type': 'text/html','Access-Control-Allow-Headers':'Content-Type,Access-Control-Allow-Headers,Access-Control-Allow-Origin,X-Powered-ByX-Powered-By','Access-Control-Allow-Origin': '*','X-Powered-By':'Poltak ganteng'});
response.end(data);
});
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function(){
console.log("Server listening on: http://localhost:%s", PORT);
});
i'm afraid that code not working properly to handle multiple request at a time. is there any way to handle multiple request and get correct response to requestor?
You want to use req/res with your socket connection, you want to send uid at each client.write end your other service responde with the same uid for conserve the relation one to one to req/res, you don't have other choice for guaranteed unicities.
The have an expensive resource as TCP client (or clients) that has to be shared among node requests, so socket-pool can help you on that.

How to send commands from client to server with Socket.io

I would like to send commands from client to server example change image url or label text. I have managed to get the connection working between server & client and the button clicks to work, but i cant manipulate the DOM from the index.js file. Is there a solid way to do this? My client side uses PHP to get data from mySQL database and i'd like to pass that data as array to server and render to view. Here is my code so far:
server: index.js -
var express = require('express');
var app = express();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get("/",function(req,res){
res.sendFile(__dirname + '/index.html');
app.use(express.static(__dirname));
});
//This is auto initiated event when Client connects to Your Machien.
io.on('connection', function(client) {
console.log('Client connected...');
client.on('test',function(msg){
console.log("i can see this in cmd console");
// i would like to do like this but it says "document is not defined"
//document.getElementById("mediaContainer").innerHTML = "Paragraph changed!";
});
});
http.listen(3000,function(){
console.log("Listening on 3000");
});
client: app.js -
$(document).ready(function () {
$("#button1").click(function(){
socket.emit('test',$("#someinput").val());
});
});
I would like it to work like this rather:
server: app.js -
$(document).ready(function () {
var socket = io.connect('http://192.168.2.65:3000');
socket.on('test',function(msg){
$("#mediaContainer").append(msg);
console.log("i cant get this to work");
});
});
Thanks :)
Got it to work. Had to make a socket.emit inside the socket.on that catch it with another server javascript file like this:
index.js:
client.on('test',function(value){
io.sockets.emit('testi1',value);
});
app.js:
socket.on('testi1',function(msg){
$("#mediaContainer").append(msg + '<br /><br />');
});
There are two sides to socket.io, BackEnd and FrontEnd.
In the code above, you tried to manipulate the DOM like document.getElementById("mediaContainer").innerHTML = "Paragraph changed!";
but this is the FrontEnd part.
How socket.io works is you use js provided by socket in the FrontEnd to emit something to the server where the socket in the BackEnd will be listening to. Then, you emit something from BackEnd in response to the received emission. You also add a listener at the FrontEnd part to this BackEnd emission and finally manipulate the DOM according to the received emission.
FrontEnd
$(document).ready(function () {
var socket = io.connect('http://192.168.2.65:3000');
$("#button1").click(function(){
socket.emit('test',$("#someinput").val());
});
socket.on('test',function(msg){
$("#mediaContainer").append(msg);
});
});
BackEnd
io.on('connection', function(client) {
console.log('Client connected...');
client.on('test',function(msg){
// If you want all including the sender to get emission
client.emit('test', msg);
// If you want all excluding the sender to get emission
client.broadcast.emit('test', msg);
});
});
This should work. Cheers!!

socket.io not emitting event from server to client on connection

I have a very basic setup with socket.io but am having trouble getting my server to send back a message once the connection has been established.
When a connection is established to my server, I want the server to send back a message to the client. I've tried to accomplish this with the following code:
Server
// Modules
var fs = require('fs');
var https = require('https');
// Certificate
var options = {
pfx: fs.readFileSync('<my cert>')
};
// Create Server
httpsServer = https.createServer(options);
// Create websocket
var io = require('socket.io')(httpsServer);
// Listen on a port
httpsServer.listen(4000,function() {
console.log('listening on *:4000');
});
io.on('connection', function(socket) {
console.log('a user connected');
socket.emit('test','you connected');
});
Client
var socket = io('https://<my server>:4000');
When I execute this code, the websocket gets established and my server console shows the message "a user connected". However, the message ['test','you connected'] does not get emitted through the socket.
The only way I've been able to get this to work is to use setTimeout() to wait 500ms before emitting the event, in which case it does work.
Why is that? How can I configure my server to automatically respond with a message as soon as the user connects?
You need to listen to the emitted event, using socket.on(event, callback);
<script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
<script>
var socket = io('https://localhost:4000');
//test is the emitted event.
socket.on("test", function(data){
console.log(data); //"you connected"
});
</script>

Categories