Rapsssito / react-native-tcp-socket

React Native TCP socket API for Android, iOS & macOS with SSL/TLS support.
MIT License
321 stars 82 forks source link

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

Closed aymensmurf closed 4 years ago

Rapsssito commented 4 years ago

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 commented 4 years ago

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

Rapsssito commented 4 years ago

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

aymensmurf commented 4 years ago

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

Rapsssito commented 4 years ago

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');