Using Socket.io to be the server and the client - javascript

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')
});

Related

Connect to a third party socket.io server

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

difference "on" and "emmit" in server and client in socket.io

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.

Node.js and Socket.io in Phaser.js not connecting socket.io/?EIO=3&transport=polling

I am able to run my node.js server, my phaser.js game runs but I get no 'connected' console.log when the game runs. I instead get this error message from the client end:
enter image description here
socket.io-1.4.5.js:1 GET http://192.168.128.184:8080/socket.io/?EIO=3&transport=polling&t=LdMR6Ro net::ERR_CONNECTION_REFUSED
SERVER:
var serverPort = 8080;
console.log("Initializing Server.");
var express = require('express');
var connect = require('connect');
var app = express();
var serv = require('http').Server(app); //.createServer(app);
var io = require('socket.io').listen(serv); //(serv,{});
console.log("Starting Server.");
var serveStatic = require('serve-static');
connect().use(serveStatic(__dirname)).listen(serverPort, function(){
console.log('Server running on ' + serverPort + ' !');
});
app.get('/',function(req, res) {
res.sendFile(__dirname + '/index.html');
});
serv.listen(8081);
var SOCKET_LIST = {};
io.on('connection',function(socket){
console.log("A user is connected");
});
io.sockets.on('connection', function(socket){
console.log('Socket connection');
});
CLIENT
var local = "http://" + document.location.host + ":8081";
var socket = io().connect(local);
In your client code you are using io().connect(local) however the correct way to connect using a specified address with your variable is io.connect(local).
Also, document.location.host will include ":8080" if it is a part of the address you used to obtain the page, therefore you need to remove it. You can try something like document.location.host.split(':')[0]

io.on is not a function

I have this code working for receiving data from my Arduino but I will like to send data back to my Arduino and get a response on my client page. I added a listening function but I keep getting io.on is not a function when I send data from my client page.
test.js
io.listen(app.listen(3000)).on('connection', function (client) {
// store client into array
clients.push(client);
// on disconnect
client.on('disconnect', function() {
// remove client from array
clients.splice(clients.indexOf(client), 1);
});
// I added this to listen for event from my chart.JS
io.on('connection', function(socket){
socket.on('LED on', function (data) {
console.log(data);
});
socket.on('LED off', function (data) {
console.log(data);
});
});
});
Your value of io is not what it should be.
The usual way of doing things is like this:
var app = require('http').createServer(handler)
var io = require('socket.io')(app);
var fs = require('fs');
app.listen(80);
io.on('connect', ...);
But I'm guessing that your value of io is something like this:
var io = require('socket.io');
That's not the same thing. That's the module handle. But, when you do it this way:
var io = require('socket.io')(app);
Then, io is a socket.io instance. You can bind listeners to an instance, not to the module handle.
In every single socket.io server-side example on this doc page, they use one of these forms:
var io = require('socket.io')(app);
var io = require('socket.io')(port);
var io = require('socket.io')(server);
with this:
io.on('connection', ....);
Nowhere do they do:
var io = require('socket.io`);
io.listen(server);
io.on('connection', ....);
That's just the wrong value for io.
Long story, shortened, you need to fix what you assign to io to be consistent with the docs. It's the return value from require('socket.io')(app); that gives you a socket.io instance object that you can then set up event handlers on.
if you are using express
var express = require('express');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
let APP_PORT=3000;
server.listen(APP_PORT,()=>{
console.log(`SERVER RUNNING ON PORT : ${APP_PORT}`);
});
io.on('connection', (socket) => {
/* SOCKET - CORE EVENTS */
socket.on('connect', (message) => {
console.log("connected: " + message+"socket_id:"+socket.id);
});
socket.on('disconnect',(data)=>{
console.log('user disconnected:' + socket.id);
});
socket.on('error', function (err){
console.log('received error from client:', socket.id,' Error :',err);
});
});

Socket.IO and Express

Here is my NodeJS server:
var express = require('express');
var app = express();
var port = process.env.PORT || 1337;
var server = app.listen(port);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function(socket){
console.log('A user connected to the chat!');
socket.on('chat message', function(msg){
console.log('message: ' + msg);
});
});
And here is my client:
var socket = io();
socket.connect('http://server:1337', { autoConnect: true});
socket.on('connect',function() {
socket.emit('chat message', "TEST");
});
And on my client side I get the following error in the console:
Cannot GET /socket.io/?EIO=3&transport=polling&t=LOIMkAR
You only need to use var socket = io.connect(), it will try to connect to the server automatically.
Unless you want to connect to a custom IP, which don't make much sense. io.connect() will do what you want to do.
After that you will use socket.emit for emitting events and socket.on for listening to events.
I've got this working with this setup similar to socket.io docs
var express = require('express');
var app = express();
var port = process.env.PORT || 1337;
var server = require('http').Server(app);
var io = require('socket.io')(server);

Categories