TransWikia.com

How can i send data and get data via angular to socket server

Stack Overflow Asked by Shyam Nair on December 30, 2021

currently i am trying to send and get the data via angular client to socket server and from socket server to angular i need to get data i able to push the data but i need to know how can i push data to the api which is there in socket server and get data from the api to socket server and emit it to client

below is my

For sending data from angular client to socket server

  • component code

    constructor(public socketService: SocketioService){

       }
    
      ngOnInit(){
         this.socketService.setupSocketConnection();
       }
     // For sending post request
       sendMsg(){
         this.socketService.sendData(this.title);
       }
        // For getting the request
       getMsg(){
    
        this.socketService.getMsg().subscribe(res => {
          console.log(res);
        })
    

Angular service code

import * as io from 'socket.io-client';

import { Observable } from 'rxjs';

socket;
  constructor() {

  }
  setupSocketConnection() {
    this.socket = io(environment.SOCKET_ENDPOINT);


  }
  // for posting data
  sendData(values){
    console.log(values);
    this.socket.emit('my message', values);
  }
   //for getting data
  getMsg(){
   return Observable.create((observer) => {
    this.socket.on('grabMsg', (message) => {
        observer.next(message);
    });
});
  }

Node server code

const app = require('express')();
const http = require('http').createServer(app);
const io = require('socket.io')(http);
app.get('/', (req, res) => {
  res.send('<h1>Hey Socket.io</h1>');
});
io.on('connection', (socket) => {
  console.log('a user connected');
  socket.on('disconnect', () => {
    console.log('user disconnected');
  });
  socket.on('my message', (msg) => {
      //here i want to consume api like 
      // localhost:3000(post) {"title":"ss"}

    console.log('message: ' + msg);
  });
  socket.on('grabMsg', () => {
        //here i want to consume api like 
      // localhost:3000(get)
      let ms = 'max'
      io.emit(ms);
  });
});
http.listen(3001, () => {
  console.log('listening on *:3001');
});

so here how can i send and post data in socket server
in short i will send data to from angular client to socket server then to some api

3 Answers

    export class LiveSocket implements OnInit {

    //define a socket
    public socket = new WebSocket(environment.SOCKET_ENDPOINT);

    ngOnInit() {

     // Add an event listener for when a connection is open
    this.socket.onopen = () => {
      console.log('WebSocket connection opened. Ready to send messages.');
      // Send a message to the server
      this.socket.send('message');
    };

    // Add an event listener for when a message is received from the server
    this.socket.onmessage = (message) => {
     //handle getting data from server 
     var data = JSON.parse(message.data);
     console.log(data)
    };
  }
}

Answered by AliAb on December 30, 2021

You can use the nodeJs eventEmitter API. So you can emit an event by eventEmitter when someone hits your endpoint(GET request) and listen that event inside your socket server and vice-versa.

More details:- Custom Events in Node.js with Express framework

Answered by gaurav soni on December 30, 2021

//server-side
socket.on('grabMsg', () => {
  let ms = 'max'
  io.emit(ms);
});

//client-side
this.socket.on('grabMsg', (message) => {
    observer.next(message);
});

In the above code you are using socket.on on both client and server-side also, use one as emit as one as on according to your requirement.

And in below code you are only emitting and there is the first parameter for emitting (any text enclosed in side quote) like below code

socket.on('grabMsg', () => {
  let ms = 'max'
  io.emit("thatText",ms);
});

the same text(thatText) should be on client-side too, like

this.socket.on('thatText', (message) => {
   console.log(message)
});

Answered by Nithin K Joy on December 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP