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

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!!

Related

How to change URL Websocket NodeJs (server/client)

I have a server node Js with express I want to use two socket with my clients in the same page server.js (contains all my controllers), suddenly I want to put the first socket under the url ("/connection"), and A second one under the url ("/giveUserConnected") that will serve me to recupir the connected users, par exemple :
client.html :
var socket = io.connect('http://127.0.0.1:9999/connection');
To contact server.js :
app.get('/connection',function (req,res) {
io.on('connection', function(socket){
console.log('a user connected');
});
});
and another socket2 in client.html :
var socket2 = io.connect('http://127.0.0.1:9999/giveUserConnected');
to contact server.js :
app.get('/giveUserConnected',function (req,res) {
io.on('connection', function(socket){
// to recuper list of users connected
});
});
but it does not work
what is the solution , thank's
You are mixing HTTP requests with socket.io requests, which are two different things.
When you provide a path name to io.connect() (in this case, /connection and /giveUserConnected), the socket.io server uses the path as the name to a namespace that the client connects to.
What I think you want is to just create an event handler for a particular message that will return the list of users. You could use acknowledgement functions for that:
// server
io.on('connection', function(socket) {
socket.on('giveUserConnected', function(fn) {
fn(listOfUsers);
});
});
// client
socket.emit('giveUserConnected', function(users) {
...
});
What listOfUsers is depends on your app.

Does socket IO need to serve HTML to work?

So, I am quite puzzled. I have a socket IO server that runs OK, and the HTML web client does connect to it. But, I can't emit anything. I'm using xampp to serve webpages, but does socket IO need to serve content for it to receive and send data? It's weird that I connect OK,but that's it, no emit function works.
Here's my code..
var io = require('socket.io')();
io.on('connection', function(client){ console.log("Connected OK."); io.emit('message',"data"); });
io.on('message', function(client){ console.log(client); });
io.listen(8080);
HTML
<script src="http://localhost:8080/socket.io/socket.io.js"></script>
<script>
// Create SocketIO instance, connect
var socket = io.connect('http://localhost:8080');
// Add a connect listener
socket.on('connect', function() {
alert('Client has connected to the server!');
});
socket.on('message', function(event) {
console.log('Received message from client!', event);
});
</script>
The code above prints "Connected OK" to the NPM console, and it alerts "Client has connected to the server!", but that's it. So my question is, does the NPM server need to serve the HTML to work, or am I doing things wrong?. I use xampp because of PHP and MySQL.
UPDATE:## The server sends to client just fine, and the client tries to send data back, and the server receives the packet. But then it reports: " engine:polling transport discarded - closing right away +0ms". Is this normal?

socket.io authentification not working on first connection

I have a NodeWebkit client which connects to a nodejs server using the socket.io library (JavaScript).
The client launches the connect procedure on the application start but the server does not acknoledge any connections... Though the client's socket has the connected attribute to "true".
You should know that I am using socketio-jwt to authentificate the connection.
Github: https://github.com/auth0/socketio-jwt
I know that the connection does work in a way because if I add :
io.sockets.on('connection', function(){console.log("hello");})
It prints hello !
So it seems that event though the connection is somehow made it doesn't want to do the auth part with the library, resulting in... Well... Nothing.
But that's not all !!
Because if I reboot the app (not the server) then the auth works most of the time ! It acts like a race condition... But I dont see how it could possibly be one... Every line of code is geting executed appart of the success callback of authentification.
I tried connecting to a remote server and on my localhost.
I also tried with an other library of socket auth but I've got the same probleme.
This is the server code:
var session = require('express-session');
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var socketioJwt = require('socketio-jwt');
io.sockets.on('connection', socketioJwt.authorize({
secret: 'some secret',
timeout: 15000 // 15 seconds to send the authentication message
})).on('authenticated', function (socket) {
console.log('[Info]: A user connected to socket = ', socket.decoded_token);
});
});
http.listen(5000, function () {
console.log('listening on *:5000');
});
And now the client code:
this.socket = io.connect('http://' + that.hostName +':' + that.port);
var token = jwt.sign({email: "someEail", pwd: "somePwd"}, fromServerSecret);
this.socket.on('connect', function () {
that.socket.emit('authenticate', {token: token}) //send the jwt
.on('authenticated', function () {
console.log("[Info]: Socket login successfull");
})
.on('unauthorized', function (msg) {
console.log("[Warning]: Socket unauthorized: " + JSON.stringify(msg.data));
throw new Error(msg.data.type);
});
});
The server side log "A user connected to socket" is never shown.
If you have an idear ! Thanks for your time.
Why is there a 'that' on socket.emit (client)? I think you should handle it within the same instance of socket.io - using same 'this' as above

using Socket.io with iOS via the socket.io Swift client

I've been trying to do basic communication between an app and my server but no matter what I do I can't seem to get it to work.
Below is my js code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
io.on('connection', function(socket){
console.log('a user connected');
io.emit("hello");
socket.on('disconnect', function() {
console.log('a user disconnected');
});
socket.on('response', function(message){
console.log(message);
});
});
http.listen(3000, function(){
console.log('listening on *:3000');
});
This should in theory be alerted when a user connects, output a message saying the user has connected and then emit an event "hello"
below the on disconnect part I am trying to communicate with the server from my iOS app. I emit a event called "response" with a string called "I got your response".
I get the "a user connected" message in the console but the message I send from the iOS app never gets printed in the console.
This the code in my app.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let socket = SocketIOClient(socketURL: "192.168.0.3:3000")
socket.on("hello") {data, ack in
socket.emit("response", "I got your response")
}
socket.connect()
}
As you can see my server side code emits the event "hello". This should trigger the socket.on("hello") and make the app emit the event "response" which makes the server print out the string sent with it.
None of this is happening apart from the message that gets printed in the console when a user connects.
An help would be greatly appreciated.
the Github repo for the framework is below
https://github.com/socketio/socket.io-client-swift
Declare and initiate your socket variable in the top of the class. As previous comments said, I think the variable is lost in the scope otherwise.
class HostSocketHandler {
let socket = SocketIOClient(socketURL: urlString)
init(){
socket.connect();
}
}

Connecting client to server using Socket.io

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

Categories