Whats the difference between socket.io and socket.io-client? - javascript

Whats the difference between socket.io and socket.io-client?
Some project I'm trying to use is using socket.io-client, but I'm used to using plain old socket.io, and it dons't really lay it out in the documentation.

The main difference I'm aware of is that with the socket.io-client library you can connect your server to another server serving socket.io events.
For example, if my server at http://localhost is emitting a data event, I can listen on another server like so:
var socket = require('socket.io')('http://localhost');
socket.on('connect', function(){
socket.on('data', function(data){
// Do something with data
});
});
and respond accordingly with the data object passed.

Related

How to import socket.io on client side - SOCKET.IO + NODE.JS

I have been trying to create an online game but when I try to use socket.on(...); or socket.emit(...) it comes up with an error like what is socket. I have seen some posts similar to this one and tried all the solutions but none worked. I have already got io.connect(...); working and it works (I assume this means I have properly set up socket.io-client). I just don't see what I am doing wrong. If you need the code you can simply request it though I don't think it was necessary. Thanks.
To use SocketIO on the client-side, first import it via
import * as io from 'socket.io-client';
Then, probably in a constructor, establish a connection to the server's ip and port running the SocketIO server
const socket = io(`172.16.1.3:81`);
Also in the constructor you will likely want to setup a function to be called when the server sends a certain message type:
socket.on("update-player", handlePlayerUpdateFunction);
and
function handlePlayerUpdateFunction(message) {
console.log(`Received message from server: ${message}`);
}
If this client does not receive the message sent from your server, then something is wrong with your server not being set up correctly to listen on the port.
After trying some things and doing some research I found the solution to my problem. Adding in var socket = io.connect(x.x.x.x:3000); my code started functioning and everything was perfect I had already imported socket.io-client trough CDNJS link on the installation guide. I just had to Initialise the variable.

How to send a message with WebSocket to a Socket.io server

I'm developing a React Native application and I want to use the WebSocket class to communicate with my Socket.io server.
I can connect to the server just fine, but I'm having problems sending messages to it using the .send() method.
I tried this on React Native:
var socket = new WebSocket("ws://host:port/socket.io/?transport=websocket");
socket.onopen = () => {
console.log("connected");
socket.send('data');
};
On my Socket.io server I have this listener that I created just for testing:
socket.on('data', function(data) {
console.log("data");
})
The connection does work, and I'm able to see that on the server too. But when I do socket.send('data') the disconnect event gets called on the server rather than the data event I wrote above. (I tested this by using a function to call the .send() method, so this does cause a disconnect on the server)
Can anyone shine some light on this?
That's because Socket.io is not exactly compatible with WebSocket - there are initial handshakes, connection fallbacks (eg. when no WS is available, use AJAX long pooling or other technique) and other things that Socket.io hides from you to make your life easier. Essentially, Socket.io should be seen as a separate protocol.
To connect to a Socket.io server, you have to use Socket.io client library.
ws.send(`42${ JSON.stringify(["message", { command: "register" }] }`), err => {
if (err) console.log("err", err);
});
This code using the ws pacakge as the example.
You need to add the 42 to tell socoket.io server that you are sending message, the {command: "register"} is the data you send, the "message" is the channel that socket.io is listening on.
io.on("message", (data) => {
console.log(data); // => {command: "register"}
});
Explain: this is the engine.io-protocol that socket.io is using. Check it's spec.
The best solution is using socket.io on both side or don't use socket.io at all.

socket.io-client object is not a function

I opened a question here earlier (Socket.io trigger events between two node.js apps?), this was much help, but I am confused out of my mind.
I keep getting object is not a function on my client side script.
A little setup, I have a front end site that is served with express localhost:9200 then I have a back end app localhost:3100 that is also served with express and I am trying to emit events from localhost:9200 to the socket.io server localhost:3100
Client script for website localhost:9200
// I have tried many different ways
var socket = io('http://localhost:3100');
var socket = io('http://localhost');
var socket = io();
EDIT
The issue was with the above of course, because io in the above case for some reason was an object when it should be a function, I came across an old post which mentioned using var socket = io.connect('http://localhost:3100'); connect and that worked, I though it was depreciated or something, I have no clue why the docs don't mention this but it fixed my issue.
All result in object is not a function. I include the client side script like this
// tried some different ways
<script src="http://localhost:3100/socket.io/socket.io.js"></script>
<script src="socket.io/socket.io.js"></script> // this is a 404
I have installed https://github.com/automattic/socket.io-client and on the server for the front end website :9200 I have set it up like.
// tried a couple ways to connect
var socket = require('socket.io-client')('http://localhost:3100');
var socket = require('socket.io-client')('http://localhost');
socket.on('connect', function(){});
socket.on('event', function(data){});
socket.on('disconnect', function(){});
I am confused on how to properly configure this so that I can get my site to emit socket events to my server and visa versa?
Well I figured it out, this is pretty ridiculous but on the client side javascript I needed to add var socket = io.connect('http://localhost:3100'); the io.connect made it work versus var socket = io('http://localhost:3100');
Maybe I missed it but the docs don't say to use io.connect https://github.com/automattic/socket.io-client whatever it works and I am happy, any thoughts on why the docs don't mention this would be great.
The difference is io.connect is pre 1.0 syntax. They changed it for whatever reason. These are the exact kind of fun surprises I have come to expect in socket.io.

How to handle socketIO when app is not running

I've been doing alot of testing with socketIO and have got stuck with handling situations where my node app is simply offline. The documentation provides no real insight into this issue.
So if i run my website and node app is simply not running, console.log gives:
GET http://[url]:[port]/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined
This is hardly surprising, how ever what i don't understand is how to handle these errors and simply have the script try to attempt a reconnect until it finally does reconnect (if ever).
My script looks like this:
<script src="http://[url]:[port]/socket.io/socket.io.js"></script>
<script>
windows.onload = function()
{
socketio = io.connect("http://[url]:[port]");
socketio.on('connecting', function() {
console.log('trying to connect');
});
socketio.on('connect', function() {
console.log('connected');
});
}
</script>
Is there a way to handle this kind of problem ?
When the server is offline, your initial <script> tag to load the Socket.io client library fails, so you never get the io object in the first place.
To retry, you can add a new <script> tag to load the same URL again and see if it succeeds.
Better yet, copy the socket.io client library to the server hosting your HTML, so that the script will always load. You can then simply handle connection errors from io.connect().
There are a few events that you can bind to.
socket.on("connect_failed", function() {
// Do whatever you wanted to do on failure
});
For a full list of exposed events check here: exposed socket.io events
Edit
Ah, I'm sorry. I misunderstood your question. I thought you wanted to handle when the socket server was offline. If you want to handle not being able to get at the socket.io client script, maybe you could check if socket is null or undefined and handle thought that. Then also fire a setTimeout function to try and load the script asynchronously after a wait period and then check if socket is still undefined or null. Or, as the other answer suggests, pack the socket.io client library with the rest of your HTML page.

Socket.io not listening

im using this simple code
Client.html
http://pastebin.com/c1C2F9MQ
Server.js
http://pastebin.com/Cqjhjfwm
Everything working fine till the last step of my client code
socket.on('add', function(data) {
socket.broadcast.emit('AAA');
});
It seems that the socket add never comes but on my server I have
socket.on('Text', function(data) {
socket.emit('add', data);
});
And I tested if socket text was coming and it does, I cant find the problem
Thanks
socket.broadcast.emit sends message to all sockets connected to server except the concerned socket. So most likely add does come to server but it broadcasts AAA which your client cannot get. Use io.sockets.emit to send to all connected sockets. Change this
socket.broadcast.emit('AAA');
to
io.sockets.emit('AAA');
Update
I too overlooked that you are calling socket.broadcast.emit from client not from server. It would have shown error on browser console, since broadcast is absent on client.
Currently your on('add') code on the client side is within the on('connect') event which is not correct...
You need to take it ouside there, so it becomes:
socket.on('connect', function () {
$('#button').click(function() {
var addtext = $('#text').val();
socket.emit('Text', addtext);
});
});
socket.on('add', function(data) {
socket.emit('AAA');
});
EDIT: I also just noticed you had socket.broadcast.emit() in your client side code. As far as I know there's no concept of broadcasting from the client. If you want to broadcast something then the client should send it to the server then the server broadcasts to the other clients.

Categories

Resources