Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How can a server send data to a specific client? #15

Closed
aymensmurf opened this issue Jan 8, 2020 · 5 comments
Closed

How can a server send data to a specific client? #15

aymensmurf opened this issue Jan 8, 2020 · 5 comments
Labels
question Question about any part of the module

Comments

@aymensmurf
Copy link

No description provided.

@aymensmurf aymensmurf changed the title How can a server send data to a specific client How can a server send data to a specific client? Jan 8, 2020
@Rapsssito Rapsssito added the question Question about any part of the module label Jan 8, 2020
@Rapsssito
Copy link
Owner

Rapsssito commented Jan 8, 2020

Following the documentation:

var server = TcpSocket.createServer((socket) => { // <--- This is the socket connected to the client
  // You may want to store the `socket` in an Array or any other data structure based on your needs
  // in order to access a specific one
  socket.on('data', (data) => {
    socket.write('Echo server', data);
  });

  socket.on('error', (error) => {
    console.log('An error ocurred with client socket ', error);
  });

  socket.on('close', (error) => {
    console.log('Closed connection with ', socket.address());
  });
}).listen(12345, '0.0.0.0');

server.on('error', (error) => {
  console.log('An error ocurred with the server', error);
});

server.on('close', () => {
  console.log('Server closed connection');
});

@aymensmurf
Copy link
Author

So to my understanding you have to make a new socket for every client. am I understanding that right?

@Rapsssito
Copy link
Owner

Rapsssito commented Jan 8, 2020

@aymensmurf, the socket is created automatically for every client. You just access it from the createServer() callback.

@aymensmurf
Copy link
Author

It still a little vague, but I will have to look more into it. Thanks for your help.

@Rapsssito
Copy link
Owner

I hope this example can help you!

const connectedSockets = []; // We store the connected sockets here
// Create the server
const server = TcpSocket.createServer((socket) => { 
  connectedSockets.push(socket); // Add the new connected socket
});

// Send a  message to the first connected client
connectedSockets[0].write('Hello server');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Question about any part of the module
Projects
None yet
Development

No branches or pull requests

2 participants