Home > OS >  (javascript) Unable to return value received in Socket.on(event)
(javascript) Unable to return value received in Socket.on(event)

Time:01-27

Basically I have a client side code that sends data to the server, the server responds with data which calls a socket.on(event) in the client side code. Within the function that is immediately run I can log the received data but I cannot return it to outside for the life of me.

function receive_data(){
    socket.off('Sent_data_to_client').on('Sent_data_to_client',(player_info));
    console.log(player_info)
}

If i try to log player_info it tells me it is undefined "Uncaught (in promise) ReferenceError: player_info is not defined". I want to return player_info as the result of the receive_data function but it is undefined.

I am new to javascript and Socket.Io as a whole, i apologise for any obvious mistakes made.

CodePudding user response:

Sockets in JS doesnt work like this. Have a specifics events.

https://nodejs.org/api/net.html#new-netsocketoptions

This is the Node JS documentation, but it doesn't matter because Node JS is based on "V8 engine", that is, it's the same.

As you can see in the documentation it indicates that there are a series of events that the socket can handle, among them the 'data', calling a callback function where you implement the necessary logic for your code. In this case, for example:

const net = require('net');

const socket = new net.Socket();

// Open a socket connection with example.com
socket.connect(80, 'example.com', () => {
  console.log('Connected');
});

socket.on('data', (data) => {
  console.log(`Recived: ${data}`);
});

socket.on('error', (error) => {
  console.log(`Error: ${error}`);
});

CodePudding user response:

You should change the function definition to accept an argument, which will be the data that the server sends.

function receive_data(){
    socket.off('Sent_data_to_client').on('Sent_data_to_client', function(player_info) {
        console.log(player_info);
        return player_info;
    });
}
  • Related