Reputation:
So I am using socket.io to transmit data real-time between a server and a client.
I am able to establish the connection between the server and the client , and the server is able to emit a socket client ID just fine.
But I am unable to emit data from the client to the server. My goal is to make the client sending data to the server to further processing but I think there is something I am doing wrong , and I can't figure out what.
Server.js here ...
var ioJSON = require('./io');
var serverPort = ioJSON.server.port;
var date = new Date();
var io = require('socket.io').listen(serverPort);
io.on('connection', function(socket){
console.log('Client connected at '+date+' with socket ID: '+ socket.client.id);
io.emit('socketClientID', socket.client.id);
});
and client.js here ...
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('socketClientID', function (socketClientID) {
console.log('Connection to server established. SocketID is',socketClientID);
});
My goal is to send data from the client to the server. I will greatly appreciate some help.
Thanks
Upvotes: 0
Views: 9796
Reputation: 56
Use socket.emit(eventName, args)
to send data in the client as such:
client.js:
var io = require('socket.io-client');
var socket = io.connect("http://localhost:3000/", {
reconnection: true
});
socket.on('socketClientID', function (socketClientID) {
console.log('Connection to server established. SocketID is',socketClientID);
socket.emit('hello_from_client', 123);
});
And in the sever listen to the event with socket.on(eventName, callback)
server.js:
var ioJSON = require('./io');
var serverPort = ioJSON.server.port;
var date = new Date();
var io = require('socket.io').listen(serverPort);
io.on('connection', function(socket){
console.log('Client connected at '+date+' with socket ID: '+ socket.client.id);
io.emit('socketClientID', socket.client.id);
socket.on('hello_from_client', function(data){
console.log(data);
});
});
Upvotes: 4